【问题标题】:How to call C++ functions of a class from a Python [duplicate]如何从Python调用类的C++函数[重复]
【发布时间】:2014-05-18 16:46:10
【问题描述】:

我尝试使用链接:Calling C/C++ from python?,但我不能这样做,在这里我有声明 extern "C" 的问题。所以请建议假设我有一个名为 'function.cpp' 的函数,我必须在 python 代码中调用这个函数。 function.cpp 是:

int max(int num1, int num2) 
 {
  // local variable declaration
  int result;

  if (num1 > num2)
    result = num1;
  else
    result = num2;

  return result; 
 }

然后我如何在 python 中调用这个函数,因为我是 C++ 的新手。我听说过“cython”,但我不知道。

【问题讨论】:

  • 就用python的max()
  • @clcto 实际上我有另一个用于 ADC 的大代码,它是用 c++ 编写的,但是我使用 python 进行编码,所以我必须在 python 中调用那个 c++ 代码。上面的c++函数只是例子

标签: python c++ function word-wrap


【解决方案1】:

由于您使用 C++,请使用 extern "C" 禁用名称修改(或 max 将导出为一些奇怪的名称,如 _Z3maxii):

#ifdef __cplusplus
extern "C"
#endif
int max(int num1, int num2) 
{
  // local variable declaration
  int result;

  if (num1 > num2)
    result = num1;
  else
    result = num2;

  return result; 
}

将其编译成一些 DLL 或共享对象:

g++ -Wall test.cpp -shared -o test.dll # or -o test.so

现在您可以使用ctypes 调用它:

>>> from ctypes import *
>>>
>>> cmax = cdll.LoadLibrary('./test.dll').max
>>> cmax.argtypes = [c_int, c_int] # arguments types
>>> cmax.restype = c_int           # return type, or None if void
>>>
>>> cmax(4, 7)
7
>>> 

【讨论】:

  • 你能告诉我,如果我在 c++ 中有类并且我必须在 python 中调用它会有什么变化
  • @Latik 如果不创建 here 中的 C 包装器,就无法将 C++ 类与 ctypes 一起使用。您还可以选择使用 SWIG,它可以更轻松地将 C++ 类包装到 Python 类中,SWIG BasicsSWIG and Python
  • thnx 寻求帮助,上面您给定的解决方案在 Ubuntu 中运行,但在 Raspberry Pi 中无法运行,因为它具有 Raspbian OS。它给出了AttributeError: ./test.dll: undefined symbol: max的错误,请给出任何解决方案。
猜你喜欢
  • 1970-01-01
  • 2021-04-06
  • 2021-01-19
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多