本文介绍了使用ctypes将C ++函数导出到python:未定义符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑该文件包含两个类似的功能:

Consider this file containing two similar functions:

#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 来说,这很好:

I wish to call these from python, for main this works fine:

import ctypes
libc = ctypes.cdll.LoadLibrary("code.so")
libc.main()

打印 main 。但是, notmain 不起作用:

Which prints main. However, notmain doesn't work:

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 ,因为 main 在c ++规范中是特殊情况。如何以相同方式导出 notmain ?或者:如何解决该异常?

I assume that main is 'exported' to the outside world (w.r.t. code.so) in a different way than notmain because main is a special case in the c++ specs. How can I 'export' notmain in the same way? Or: how can I fix the exception?

编辑如@abdallahesam所建议,我添加了 estern C 更改为 notmain ,但这并没有改变(或解决)问题:

EDIT As suggested by @abdallahesam I added estern "C" to notmain, this did not change (or solve) the problem:

#include <iostream>

int main()
{
  std::cout << "main\n";
}

extern "C" {
  int notmain()
  {
std::cout << "notmain\n";
  }
}

更正

该建议确实解决了问题,我只需要重新启动(i)python会话即可。显然,这很重要:)

The suggestion did solve the problem, I just needed to restart the (i)python session. Apparently this matters :)

推荐答案

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

I think you should add extern "C" to your notmain function header to prevent c++ compiler from altering function name.

这篇关于使用ctypes将C ++函数导出到python:未定义符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:43