如何从Python调用C++类的函数

5 投票
1 回答
6058 浏览
提问于 2025-04-18 06:55

我试过这个链接:从Python调用C/C++?,但我还是没能做到。我在声明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',但我对它一点都不了解。

1 个回答

7

因为你使用的是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
>>> 

撰写回答