从 python 个 ctypes 调用 CPP 函数

Calling CPP function from python ctypes

我知道 - 有十亿半个类似的问题。我尝试了大部分(甚至全部),其中 none 有帮助。

我需要从 python.

调用 c++ 11 函数
// test.cpp
#define DLL_PUBLIC extern "C" __attribute__ ((visibility ("default")))
DLL_PUBLIC int init_module(void** module, void** error);

我正在构建如下:

# Make
gcc -std=c++11 -c -Wall -Werror -fPIC test.cpp
gcc -shared -o libtest.so test.o

Python代码:

# test.py
test_lib = CDLL('./libtest.so')

异常:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    test_lib = CDLL('./libtest.so', mode=1 )
  File "/usr/lib/python3.5/ctypes/__init__.py", line 347, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: ./libtest.so: undefined symbol: _ZTVN10__cxxabiv120__si_class_type_infoE

我已经尝试在加载之前加载 clib 和 stdlib - 没有帮助。 有什么通用的方法可以指定我的库需要在加载时加载所有依赖项吗? (如在 windows dll 中?)

谢谢,抱歉打扰了。

您似乎正在使用默认为 C 模式的 gcc 命令进行编译和 linking。对于 C++ 模式,您应该使用 g++ 命令。

对于编译来说这不是问题,因为 GCC 检测到 .cpp 扩展并切换到 C++ 模式,但是对于 linking 你真的需要告诉GCC 在 C++ 模式下为 link,否则它不会 link 与 C++ 运行时库。

注意:g++ 大致等同于 gcc -xc++ -lstdc++ -shared-libgcc。因此,如果您真的想使用 gcc 命令,这可能是适合您的解决方案。有关 compile and link 选项的更多详细信息,请参阅 GCC 文档。