【问题标题】:Export C++ function to python using ctypes: undefined symbol使用 ctypes 将 C++ 函数导出到 python:未定义符号
【发布时间】: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


【解决方案1】:

我认为您应该将 extern "C" 添加到您的 notmain 函数头中,以防止 c++ 编译器更改函数名称。

【讨论】:

  • 谢谢,我按照OP中的说明尝试了这个,但没有解决问题。
  • 更正:我需要重新启动 ipython 会话才能使其正常工作。
  • 无论你使用extern "C" ... 还是extern "C" {...} if ... 只是一种说法。反正我都试过了,效果很好。
  • 还是谢谢你!否则,这可能会花费我数小时来解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2019-02-15
相关资源
最近更新 更多