python调用c/c++库

 下面这段文字是从一个讨论中剪裁出来的。目前没有时间翻译,先放到这里,等有时间再做翻译。 

不过不用英文的解释,其实只用看代码就知道怎么用了。

 

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

problems
. 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{ 
    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.

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 
 




上面是以linux举例,其实windows下面也是一样,只不过动态库不在是以so问后缀,而是以dll为后缀,其他几乎一模一样。

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

    分享到:

留言

你的邮箱是保密的 必填的信息用*表示