I like ctypes a lot,swig always tended to give me

. Also ctypes has the advantage that you don’t 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{ 
        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, -o  foo.

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

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

Once you have that you can call it like

f = Foo() #and you will see "Hello" on the screen 


版权所有,禁止转载. 如需转载,请先征得博主的同意,并且表明文章出处,否则按侵权处理.


Leave a Reply

Your email address will not be published. Required fields are marked *