【发布时间】:2016-03-26 15:15:10
【问题描述】:
考虑这个文件包含两个相似的函数:
#include <iostream>
int main()
{
std::cout << "main\n";
}
int notmain()
{
std::cout << "notmain\n";
}
我把它编译成一个共享库:
g++ -shared -Wl,-soname,code -o code.so -fPIC code.cpp
我希望从 python 调用这些,因为 main 这工作正常:
import ctypes
libc = ctypes.cdll.LoadLibrary("code.so")
libc.main()
打印main。但是,notmain 不起作用:
import ctypes
libc = ctypes.cdll.LoadLibrary("code.so")
libc.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
我假设 main 以不同于 notmain 的方式“导出”到外部世界(w.r.t. code.so),因为 main 是 c++ 规范中的一个特例。我怎样才能以同样的方式“导出”notmain?或者:如何修复异常?
编辑根据@abdallahesam 的建议,我将estern "C" 添加到notmain,这并没有改变(或解决)问题:
#include <iostream>
int main()
{
std::cout << "main\n";
}
extern "C" {
int notmain()
{
std::cout << "notmain\n";
}
}
更正
该建议确实解决了问题,我只需要重新启动 (i)python 会话。显然这很重要:)
【问题讨论】:
-
有趣的是,nm 将 main-function 显示为符号
00000000000008a5 T main,而 notmain-function 显示为带有“签名添加”的符号:00000000000008c6 T _Z7notmainv -
我遇到了同样的问题,唯一的解决方案是重新启动 python 会话。在我的情况下,我需要它在不重新启动 python 会话的情况下工作。有什么线索吗?
标签: python c++ shared-libraries python-3.4 ctypes