Import C++ function into Python program

Here is a little working completion of the simple example above. Although the thread is old, I think it is helpful to have a simple all-embracing guide for beginners, because I also had some problems before.

function.cpp content (extern “C” used so that ctypes module can handle the function):

extern "C" int square(int x)
{
  return x*x;
}

wrapper.py content:

import ctypes
print(ctypes.windll.library.square(4)) # windows
print(ctypes.CDLL('./library.so').square(4)) # linux or when mingw used on windows

Then compile the function.cpp file (by using mingw for example):

g++ -shared -c -fPIC function.cpp -o function.o

Then create the shared object library with the following command (note: not everywhere are blanks):

g++ -shared -Wl,-soname,library.so -o library.so function.o

Then run the wrapper.py an the program should work.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)