How to call C++ functions of a class from a Python

2019-05-09 19:16发布

问题:

This question already has an answer here:

  • Calling C/C++ from Python? 14 answers

I tried with the link: Calling C/C++ from python?, but I am not able to do the same, here I have problem of declaring extern "C".so please suggest suppose I have the function called 'function.cpp' and I have to call this function in the python code. function.cpp is:

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

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

  return result; 
 }

Then how i can call this function in python, as I am new for c++. I heard about the 'cython' but I have no idea about it.

回答1:

Since you use C++, disable name mangling using extern "C" (or max will be exported into some weird name like _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; 
}

Compile it into some DLL or shared object:

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

now you can call it using 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
>>>