Dmitry Trofimov
Dmitry Trofimov

Reputation: 7601

How to create Cython cdef public class from C

I have following test.pyx

cdef public class Foo[object Foo, type FooType]:  
   cdef public char* foo(self):  
       r = "Foo"  
       return r  

cython compiles that code to test.h and test.c and everything looks fine, but I can't figure out how to create Foo object from C-code.

Even if I create it using Cython function:

cdef public Foo create_Foo():
   return Foo()

I can't figure out how to invoke foo method.

Thanks.

Upvotes: 5

Views: 2190

Answers (2)

Dmitry Trofimov
Dmitry Trofimov

Reputation: 7601

That answer I've got in Cython User Group:

Public should probably be disallowed for methods, since calling the functions directly would break subclassing. If you need to invoke the method from C, write a wrapper function for each method that takes the object as extra argument, and invoke the method. E.g.

cdef char *foo_wrapper(Foo obj):
   return obj.foo()

It's inconvenient if you have many methods, so if you have control over the design of Foo to begin with, don't use methods but use functions instead.

Upvotes: 5

Niklas R
Niklas R

Reputation: 16870

Specify create_ foo as def or cpdef. cdef - ed functions are converted entirely in C Code and will not be exposed to the Python module.

Upvotes: 3

Related Questions