New to Cython ... may not seem to properly wrap listings

I'm new to Cython, but I'm trying to find out more, as I would like to call a fairly large and complex set of C / C ++ code directly from Python.

I managed to complete the examples in order and even managed to wrap up a very small part of the main project that I am working on. But I'm stuck on enumeration wraps.

I tried to snatch what I am trying to do in a very simplified example.

Here is the C code in myenum.h

// myenum.h enum strategy { slow = 0, medium = 1, fast = 2 }; 

Here is what I thought would work as a wapper in pymyenum.pyx

 # distutils: language = c cdef extern from "myenum.h" namespace "myenum": cdef enum strategy: slow, medium, fast 

And here is my setup.py

 from distutils.core import setup from Cython.Build import cythonize setup(ext_modules = cythonize( "pymyenum.pyx", # our Cython source sources=["myenum.h"], # additional source file(s) language="c", # generate C code )) 

In this directory I run

 python setup.py build_ext --inplace 

and I get my pymyenum.so that I can import! Yes! But I can’t access the strategy.

 In [1]: import pymyenum In [2]: pymyenum. pymyenum.c pymyenum.pyx pymyenum.so In [2]: pymyenum.strategy --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-2-80980071607b> in <module>() ----> 1 pymyenum.strategy AttributeError: 'module' object has no attribute 'strategy' In [3]: from pymyenum import strategy --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-3-9bae6637f005> in <module>() ----> 1 from pymyenum import strategy ImportError: cannot import name strategy 

I cannot find the right example to get me out of this. Thanks in advance to everyone who can help!

Matt

+6
source share
1 answer

It will work the way you want if you use this pymyenum.pyx:

 # distutils: language = c cdef extern from "myenum.h": cpdef enum strategy: slow, medium, fast 

Note that your header is a c header without the namespace 'myenum', and cpdef for everything you want to export to python. cdef just makes things available in cython code.

+6
source

All Articles