【发布时间】:2021-11-17 09:22:15
【问题描述】:
背景
我有一些用 C++ 编写的函数,它们需要很高的实时性能。我想快速将这些函数导出为动态链接库以暴露给 Python,以便我可以进行一些高级编程。
在这些函数中,为了方便使用,我使用
代码示例
我发现核心问题是我不能事件导出 python 对象。编译源码为dll并使用ctypes加载后,结果显示
OSError: exception: access violation reading 0x0000000000000008
C++ 代码:
#include <Python.h>
#ifdef _MSC_VER
#define DLL_EXPORT __declspec( dllexport )
#else
#define DLL_EXPORT
#endif
#ifdef __cplusplus
extern "C"{
#endif
DLL_EXPORT PyObject *test3() {
PyObject* ptr = PyList_New(10);
return ptr;
}
#ifdef __cplusplus
}
#endif
Python 测试代码:
if __name__ == "__main__":
import ctypes
lib = ctypes.cdll.LoadLibrary(LIB_DLL)
test3 = lib.test3
test3.argtypes = None
test3.restype = ctypes.py_object
print(test3())
环境配置
Clion with Microsoft Visual Studio 2019 Community,arch 是 amd64。
我知道,正确的方法是使用推荐的方法将使用 Python/C Api 的 C++ 源代码包装到模块中,但似乎我必须编写很多代码。有人可以帮忙吗?
【问题讨论】: