python调用c++动态库_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:

#includeclassFoo{public:voidbar(){std::cout<<"Hello"<

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

extern"C"{Foo*Foo_new(){returnnewFoo();}voidFoo_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 ctypesimportcdll

lib=cdll.LoadLibrary('./libfoo.so')classFoo(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为后缀,其他几乎一模一样。

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

分享到:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值