我可以使用 cython 创建一个包含以 python 代码为核心的导出 C 函数的共享库吗?就像用 C 包装 Python 一样?
它要在插件中使用。 tk
最佳答案
使用 Cython,您可以使用 cdef
关键字(和 public
...重要!)编写声明为 C 函数的函数,并使用 Python 内部代码:
yourext.pyx
cdef int public func1(unsigned long l, float f):
print(f) # some python code
注意:以下假设我们在驱动器 D:\的根目录下工作
构建 (setup.py)
from distutils.core import setup
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
name = 'My app',
ext_modules = cythonize("yourext.pyx"),
)
然后运行python setup.py build_ext --inplace
运行 setup.py 后(如果您使用 distutils
),您将获得 2 个感兴趣的文件:
- yourext.h
- yourext.c
查看 .c
将显示 func1
最终是一个 C 函数。
这两个文件就是我们完成其余操作所需的全部内容。
测试用C主程序
// test.c
#include "Python.h"
#include "yourext.h"
main()
{
Py_Initialize(); // start python interpreter
inityourext(); // run module yourext
func1(12, 3.0); // Lets use shared library...
Py_Finalize();
}
由于我们本身不使用扩展名(.pyd
),因此我们需要在头文件中做一些小技巧/技巧来禁用“DLL 行为”。在“yourext.h”的开头添加以下内容:
#undef DL_IMPORT # Undefines DL_IMPORT macro
#define DL_IMPORT(t) t # Redefines it to do nothing...
__PYX_EXTERN_C DL_IMPORT(int) func1(unsigned long, float);
将“yourext”编译为共享库
gcc -shared yourext.c -IC:\Python27\include -LC:\Python27\libs -lpython27 -o libyourext.dll
然后编译我们的测试程序(链接到DLL)
gcc test.c -IC:\Python27\include -LC:\Python27\libs -LD:\ -lpython27 -lyourext -o test.exe
最后运行程序
$ test
3.0
这并不明显,还有很多其他方法可以实现相同的目标,但这可行(看看 boost::python ,...,其他解决方案可能更适合您的需求)。
我希望这能回答你的一些问题,或者至少给你一个想法......
关于python - 创建一个公开Python代码的DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20459028/