pythonc++cython

compile c++ code into pyd with cython


Cython compiles a python-like code to a C++ Code then it uses gcc/g++ to compile it into a library like pyd.

Lets say i would write my code in pure C++ then compile it into pyd to use it in Python for example lets say i have the following C++ module

int sum(int a, int b){
    return a + b
}

Is it possible to compile that code into pyd without using something like PyObject, Ctype ... etc? or does the code must be in the first place written with Cython Syntax to be compatible with Python ?


Solution

  • I am not an expert on this, but as noone answered yet, here is my opinion:

    You should use cython if you want to avoid using PyObject structures and "Python.h" in C.

    The trouble is that **.pyd is a specially prepaired DLL that exposes import() friendly interface, that, I think, includes returning PyObjects.

    But using ctypes on normal DLL or shared object lib isn't hard:

    >>> import ctypes
    >>> mysum = ctypes.cdll.LoadLibrary("mysum.so") # Or DLL
    >>> print mysum.sum(2, 3)
    5
    

    You'll just have to export the sum function to be available from dynamic library and compile your code as such.