Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Cython cdef public class from C

Tags:

c

cython

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.

like image 527
Dmitry Trofimov Avatar asked Jun 18 '12 00:06

Dmitry Trofimov


People also ask

Does Cython use C or C++?

Cython improves the use of C-based third-party number-crunching libraries like NumPy. Because Cython code compiles to C, it can interact with those libraries directly, and take Python's bottlenecks out of the loop.

What is Cdef in Cython?

Since Cython is based on C runtime, it allows you to use cdef and cpdef . cdef declares function in the layer of C language. As you know (or not?) in C language you have to define type of returning value for each function. Sometimes function returns with void , and this is equal for just return in Python.

Can you use C++ in Cython?

Overview. Cython has native support for most of the C++ language. Specifically: C++ objects can be dynamically allocated with new and del keywords.

Is Cython object oriented?

Cython is fast at the same time provides flexibility of being object-oriented, functional, and dynamic programming language. One of the key aspects of Cython include optional static type declarations which comes out of the box.


2 Answers

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.

like image 147
Dmitry Trofimov Avatar answered Oct 14 '22 05:10

Dmitry Trofimov


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.

like image 30
Niklas R Avatar answered Oct 14 '22 05:10

Niklas R