5

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.

Community
  • 1
  • 1
lkkkk
  • 1,999
  • 4
  • 23
  • 29
  • Check [boost python library](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/v2/reference.html) – πάντα ῥεῖ May 18 '14 at 16:47
  • Just use python's [`max()`](https://docs.python.org/2/library/functions.html#max) – clcto May 18 '14 at 16:49
  • @clcto actually i have another big code for ADC which is in c++, but i am using python for coding, so I have to call that c++ code in python. The above c++ function is just example – lkkkk May 18 '14 at 16:52

1 Answers1

7

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
>>> 
  • Can you please tell, what will be changes if I have classes in c++ and I have to call that in python – lkkkk May 19 '14 at 07:15
  • @Latik It's not possible to use C++ classes with `ctypes` without creating C wrapper like in [here](http://stackoverflow.com/questions/18590465/calling-complicated-c-functions-in-python-linux/18591226#18591226). You can also choose to use SWIG, which makes it much easier to wrap C++ classes into Python classes, [SWIG Basics](http://www.swig.org/Doc3.0/SWIG.html#SWIG), [SWIG and Python](http://www.swig.org/Doc3.0/Python.html#Python). –  May 19 '14 at 18:36
  • thnx for help, the above your given solution is working in Ubuntu but it is not working in Raspberry Pi as it has Raspbian OS. It is giving error as `AttributeError: ./test.dll: undefined symbol: max` please give any solution. – lkkkk May 24 '14 at 09:55