Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C/C++ from Python? [closed]

Tags:

c++

python

c

What would be the quickest way to construct a Python binding to a C or C++ library?

(I am using Windows if this matters.)

like image 853
shoosh Avatar asked Sep 28 '08 05:09

shoosh


People also ask

Can you call C from Python?

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

Can I use C++ code in Python?

The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler.


2 Answers

ctypes module is part of the standard library, and therefore is more stable and widely available than swig, which always tended to give me problems.

With ctypes, you need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against.

Suppose you have a simple C++ example class you want to talk to in a file called foo.cpp:

#include <iostream>  class Foo{     public:         void bar(){             std::cout << "Hello" << std::endl;         } }; 

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

extern "C" {     Foo* Foo_new(){ return new Foo(); }     void Foo_bar(Foo* foo){ foo->bar(); } } 

Next you have to compile this to a shared library

g++ -c -fPIC foo.cpp -o foo.o g++ -shared -Wl,-soname,libfoo.so -o libfoo.so  foo.o 

And finally you have to write your python wrapper (e.g. in fooWrapper.py)

from ctypes import cdll lib = cdll.LoadLibrary('./libfoo.so')  class Foo(object):     def __init__(self):         self.obj = lib.Foo_new()      def bar(self):         lib.Foo_bar(self.obj) 

Once you have that you can call it like

f = Foo() f.bar() #and you will see "Hello" on the screen 
like image 61
Florian Bösch Avatar answered Sep 30 '22 01:09

Florian Bösch


You should have a look at Boost.Python. Here is the short introduction taken from their website:

The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools -- just your C++ compiler. It is designed to wrap C++ interfaces non-intrusively, so that you should not have to change the C++ code at all in order to wrap it, making Boost.Python ideal for exposing 3rd-party libraries to Python. The library's use of advanced metaprogramming techniques simplifies its syntax for users, so that wrapping code takes on the look of a kind of declarative interface definition language (IDL).

like image 25
Ralph Avatar answered Sep 30 '22 02:09

Ralph