0

I have a cython file random.pyx like this:

cdef public int get_random_number():
    return 4

with setup.py like this:

from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension

extensions = [Extension("librandom", ["random.pyx"])]
setup(
    ext_modules = cythonize(extensions)
)

Then I get a dynamic library librandom.so, now I want to use this so file in c++ instead of python.

#include <stdio.h>
#include "random.h"

int main() {
    printf("%d\n",get_random_number());
    return 0;
}

now I get error like this when I compile g++ -o main main.cpp -lrandom -L. -Wl,-rpath,"\$ORIGIN":

In file included from main.cpp:2:0:
random.h:26:1: error: ‘PyMODINIT_FUNC’ does not name a type
 PyMODINIT_FUNC initrandom(void);
roger
  • 9,063
  • 20
  • 72
  • 119
  • 1
    You will need to add python-includes as well as python library to your build, also you cannot use the functionality of the cython module without innitializing it first. That answer fills the gap from the cython tutorial and may be helpful to you: https://stackoverflow.com/a/45424720/5769463 – ead Sep 28 '17 at 13:33

1 Answers1

1

Try to change your c codes to:

#include <stdio.h>
#include "Python.h"
#include "random.h"

int main() {
    Py_Initialize(); 
    PyInit_random(); // see "random.h"
    int r = get_random_number();
    Py_Finalize();
    printf("%d\n", r);
    return 0;
}

Note that to run the executable, you cannot get rid of the python environment.

Also see How to import Cython-generated module from python to C/C++ main file? (programming in C/C++)

oz1
  • 938
  • 7
  • 18