使用 ctypes 将 C++ 函数导出到 python:未定义的符号
Export C++ function to python using ctypes: undefined symbol
考虑这个包含两个相似函数的文件:
#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 'exported' 对外界(w.r.t。code.so)的方式与 notmain
不同,因为 main
是一个C++规范中的特例。我怎样才能用同样的方式 'export' notmain
呢?或者:如何修复异常?
EDIT 正如@abdallahesam 所建议的,我将 estern "C"
添加到 notmain
,这并没有改变(或解决)问题:
#include <iostream>
int main()
{
std::cout << "main\n";
}
extern "C" {
int notmain()
{
std::cout << "notmain\n";
}
}
更正
这个建议确实解决了问题,我只需要重新启动 (i)python 会话。显然这很重要:)
我认为您应该将 extern "C" 添加到 notmain 函数头中,以防止 c++ 编译器更改函数名称。
考虑这个包含两个相似函数的文件:
#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 'exported' 对外界(w.r.t。code.so)的方式与 notmain
不同,因为 main
是一个C++规范中的特例。我怎样才能用同样的方式 'export' notmain
呢?或者:如何修复异常?
EDIT 正如@abdallahesam 所建议的,我将 estern "C"
添加到 notmain
,这并没有改变(或解决)问题:
#include <iostream>
int main()
{
std::cout << "main\n";
}
extern "C" {
int notmain()
{
std::cout << "notmain\n";
}
}
更正
这个建议确实解决了问题,我只需要重新启动 (i)python 会话。显然这很重要:)
我认为您应该将 extern "C" 添加到 notmain 函数头中,以防止 c++ 编译器更改函数名称。