Her*_*ert 6 c++ python ctypes shared-libraries python-3.4
考虑这个包含两个相似函数的文件:
#include <iostream>
int main()
{
std::cout << "main\n";
}
int notmain()
{
std::cout << "notmain\n";
}
Run Code Online (Sandbox Code Playgroud)
我把它编译成一个共享库:
g++ -shared -Wl,-soname,code -o code.so -fPIC code.cpp
Run Code Online (Sandbox Code Playgroud)
我想从 python 中调用这些,因为main这很好用:
g++ -shared -Wl,-soname,code -o code.so -fPIC code.cpp
Run Code Online (Sandbox Code Playgroud)
哪个打印main。但是,notmain不起作用:
import ctypes
libc = ctypes.cdll.LoadLibrary("code.so")
libc.main()
Run Code Online (Sandbox Code Playgroud)
输出:
import ctypes
libc = ctypes.cdll.LoadLibrary("code.so")
libc.notmain()
Run Code Online (Sandbox Code Playgroud)
我假设 main 以不同于notmain因为main是 c++ 规范中的特殊情况的方式“导出”到外部世界(wrt code.so)。我怎样才能notmain以同样的方式“导出” ?或者:我该如何修复异常?
编辑正如我添加estern "C"到的@abdallahesam 所建议的那样notmain,这并没有改变(或解决)问题:
<ipython-input-63-d6bcf8b748de> in <module>()
----> 1 libc.notmain()
/usr/lib/python3.4/ctypes/__init__.py in __getattr__(self, name)
362 if name.startswith('__') and name.endswith('__'):
363 raise AttributeError(name)
--> 364 func = self.__getitem__(name)
365 setattr(self, name, func)
366 return func
/usr/lib/python3.4/ctypes/__init__.py in __getitem__(self, name_or_ordinal)
367
368 def __getitem__(self, name_or_ordinal):
--> 369 func = self._FuncPtr((name_or_ordinal, self))
370 if not isinstance(name_or_ordinal, int):
371 func.__name__ = name_or_ordinal
Run Code Online (Sandbox Code Playgroud)
更正
该建议确实解决了问题,我只需要重新启动 (i)python 会话。显然这很重要:)