This question already has answers here:
Calling C/C++ from Python? [closed]

(12个答案)


已关闭6年。




我尝试了链接:Calling C/C++ from python?,但是我无法做到这一点,在这里我有一个声明外部变量“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”,但对此一无所知。

最佳答案

由于您使用的是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
>>>

09-10 01:46
查看更多