How to call C++ functions of a class from a Python [duplicate]

末鹿安然 提交于 2019-12-05 15:00:51

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
>>> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!