Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to Cython...can't seem to properly wrap enums

I'm pretty new to Cython but I'm trying to learn more, as I'd like to be able to call a fairly large and complicated set of C/C++ code directly from Python.

I've been able to run through the examples OK and have even been able to wrap a very small part of the main project on which I'm working. But I've gotten stuck on wrapping enums.

I've tried to break out what I'm trying 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! Yeah! But I can't access 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 can't seem to find the right example to get me out of this. Thanks in advance for anyone who can help!

Matt

like image 486
Matt Bellis Avatar asked May 20 '16 15:05

Matt Bellis


1 Answers

It will work how 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 with no 'myenum' namespace, and it's cpdef for anything you want exported to python. cdef just makes things available in cython code.

like image 192
patstew Avatar answered Sep 22 '22 12:09

patstew