Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import C++ function into Python program

I'm experimenting with python functions right now. I've found a way to import python functions into c/c++ code, but not the other way around.

I have a c++ program written and it has a certain function in it. I'd like to "import" the compiled c++ program into my python script and call the c++ function.

For simplicity, say the c++ function is as simple as:

int square(x) {   return x*x; } 

and the compiled program is named Cprog.

I'd like my python script to be something like:

import Cprog  print Cprog.square(4) 

Is this possible? I've searched the internet to no avail and I'm hoping one of you gurus might have a clever way of going about this...

like image 663
Nick Avatar asked Nov 22 '10 01:11

Nick


People also ask

Can you call C functions in Python?

We can call a C function from Python program using the ctypes module.

Can we import C file in Python?

Perhaps the subprocess module can help. In addition to the question linked in the previous comment (which is about calling C functions from Python), check out Calling an external command in Python. You may be able to compile our C code normally into a program and call that program from Python.

How does Python call C code?

cPython has two main ways to call C code: either by loading a shared library and calling its symbols, or by packing C code as Python binary modules and then calling them from Python code as though they were ordinary Python modules, which is how high performance stuff in the standard library is implemented - e.g. json.

Can you use C and Python together?

Any code that you write using any compiled language like C, C++, or Java can be integrated or imported into another Python script. This code is considered as an "extension." A Python extension module is nothing more than a normal C library.


1 Answers

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.

like image 152
dolby Avatar answered Sep 18 '22 14:09

dolby