almost 4 years ago

Calling C code

  1. We create a shared object file of our c source code.
  2. Then use Python ctypes package load the shared object file and call the function we need to call.

called.c

int call_me (int a, int b)
{
    int s = a * b;
    return s;
}

To create a shared object file type the following

gcc -shared -o c_called.so -fPIC called.c

We will have a shared file name c_called.so in the current diretory

caller.py

from ctypes import cdll
lib_c = cdll.LoadLibrary('./c_called.so') # do not forget the ./

print (lib_c.call_me(3,5))

Calling C++ code

Since ctypes can only talk to C functions, you need to provide those declaring them as extern
"C"

called.cpp

extern "C" {
    int call_me (int p1,int p2)
    {
      int s = p1 * p2;
          return s;
    };
};

To create a shared object file type the following

// g++ -shared -o cpp_called.so -fPIC called.cpp

We will have a shared file name cpp_called.so in the current diretory

caller.py

from ctypes import cdll
lib_cpp = cdll.LoadLibrary('./cpp_called.so') # do not forget the ./

print (lib_cpp.call_me(3,5))

Note

The c and the cpp code above are very similar. We are not showing any C++ object oriented feature. There is a good description in SO for that.

← Call Javascript functions from Java code Python Wrapper for C++ classes →