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

lkk*_*kkk 4 c++ python function word-wrap

我尝试使用链接:从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; 
 }
Run Code Online (Sandbox Code Playgroud)

那么我如何在python中调用这个函数,因为我是c ++的新手.我听说过'cython',但我不知道.

小智 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; 
}
Run Code Online (Sandbox Code Playgroud)

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

g++ -Wall test.cpp -shared -o test.dll # or -o test.so
Run Code Online (Sandbox Code Playgroud)

现在你可以用它来调用它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
>>> 
Run Code Online (Sandbox Code Playgroud)