我可以在C++中使用cython动态库编译吗?
问题描述:
我有一个cython
文件random.pyx
这样的:我可以在C++中使用cython动态库编译吗?
cdef public int get_random_number():
return 4
与setup.py
这样的:
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)
)
然后我得到一个动态库librandom.so
,现在我想用这个so
文件在C++,而不是蟒蛇。
#include <stdio.h>
#include "random.h"
int main() {
printf("%d\n",get_random_number());
return 0;
}
现在我得到错误这样当我编译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);
答
试图改变你的C代码:
#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;
}
注意,运行可执行文件,你不能让摆脱python环境。
另见How to import Cython-generated module from python to C/C++ main file? (programming in C/C++)
您将需要为Python库添加蟒蛇,包括和你的身材,你也可以不先innitializing它使用用Cython模块的功能。该答案填补了cython教程的空白,可能对您有所帮助:https://stackoverflow.com/a/45424720/5769463 – ead