Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose a python class to c++ using cython

Tags:

c++

python

cython

How do I expose a python objects to C++ using cython? I understand how it can be done for functions, but not sure if this is even possible for a class.

Essentially, I have a data structure which is written in cython which has to be populated by C++. Once populated, c++ code will call a cython method and pass that object. The cython code in that method should be able to access the object's data.

like image 282
user3612009 Avatar asked Sep 26 '22 08:09

user3612009


1 Answers

The answer is to use "public extension types".

A trivial example is:

cdef extern from "cpp_file.hpp":
    void modifyMyClass(MyClass)

cdef public class MyClass [object TheNameThisWillHaveInC, type TheNameTheTypeWillHaveInC]:
    cdef int a
    cdef int b
    
def example():
    cdef MyClass a = MyClass()
    modifyMyClass(a)

Note the "public class MyClass". You also need to specify two names: one for the name of the struct used to represent MyClass, and one for the name that the type object will have.

Running Cython on it generates a header file containing the following (I've only copied the interesting bits).

struct TheNameThisWillHaveInC {
  PyObject_HEAD
  int a;
  int b;
};

__PYX_EXTERN_C DL_IMPORT(PyTypeObject) TheNameTheTypeWillHaveInC;

You simply include that header file in your C++ code. The example function I've given would appear as follows in C++:

void modifyMyClass(TheNameThisWillHaveInC* obj) {
   obj->a = 5; // etc
}

I don't think the fact that you're using C++ rather than C changes much. The only thing you'd need to do is run Cython in C++ mode (specify the language in setup.py to avoid name mangling issues.

like image 144
DavidW Avatar answered Sep 29 '22 21:09

DavidW