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.

3
  • Check boost python library Commented May 18, 2014 at 16:47
  • Just use python's max() Commented May 18, 2014 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 Commented May 18, 2014 at 16:52

1 Answer 1

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
>>> 
Sign up to request clarification or add additional context in comments.

3 Comments

Can you please tell, what will be changes if I have classes in c++ and I have to call that in python
@Latik It's not possible to use C++ classes with ctypes without creating C wrapper like in here. You can also choose to use SWIG, which makes it much easier to wrap C++ classes into Python classes, SWIG Basics, SWIG and Python.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.