我可以在 c++ 中使用带有 cython 的动态库编译吗?

Can I use dynamic library compile with cython in c++?

本文关键字:动态 编译 cython c++ 我可以      更新时间:2023-10-16

我有一个cython文件random.pyx如下所示:

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,现在我想在 c++ 而不是 python 中使用这个so文件。

#include <stdio.h>
#include "random.h"
int main() {
printf("%dn",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("%dn", r);
return 0;
}

请注意,要运行可执行文件,您无法摆脱 python 环境。

另请参阅如何将 Cython 生成的模块从 python 导入到 C/C++ 主文件?(C/C++编程)