ubuntu中python调用C/C++方法之动态链接库详解
安装boost
python调用C/C++的方法有很多,本文使用boost.python。考虑到后期有好多在boost上的开发工作,所以boost一并安装了,Boost库分为两个部分来使用,一是直接使用对应的头文件,二是需要编译安装相应的库才可以使用。
具体安装方法可以参考:https://www.jb51.net/article/150380.htm
这里使用:
sudo apt-get install libboost-all-dev
服务端
序列化后发送
main.cpp:
#include <iostream> #include "libUO.h" int main() { UO_C_Socket t; // t.StartSocketServer("",4121); boost::thread t1(boost::bind(&UO_C_Socket::StartSocketServer,&t,"",4121)); sleep(2); // boost::thread t2(boost::bind(&UO_C_Socket::StartSocketClient,&t,"127.0.0.1",4121)); // t2.join(); t1.join(); return 0; }
客户端
客户端在UO_BaseFun.h里实现基本功能,将其进行封装并通过boost_python导出。特别注意,这里BOOST_PYTHON_MODULE中的名字需和最后make出的so文件
同名,不然会出现错误,错误名字忘记了
UO_libdll_py_wrap.cpp:
#include <boost/python.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include "UO_BaseFun.h" BOOST_PYTHON_MODULE(UO_BaseFun) //python模块 { // boost::python::class_<UO_C_Socket,boost::noncopyable>("UO_C_Socket") boost::python::class_<UO_C_Socket>("UO_C_Socket") .def("StartSocketClient",&UO_C_Socket::StartSocketClient) // .def("getname",&student::getname) // .def("setage",&student::setage) // .def("getage",&student::getage) // .add_property("name",&student::getname,&student::setname) // .add_property("age",&student::getage,&student::setage) ; }
特别注意的是makefile中编译和连接的区别,其中出现的未定义符号错误需加上动态链接库-lboost_filesystem等。出现找不到pyconfig.h错误需包含
-I/usr/include/python2.7。make完了之后生成UO_BaseFun.so文件
makefile:
UO_BaseFun.so:UO_libdll_py_wrap.o g++ UO_libdll_py_wrap.o -o UO_BaseFun.so -shared -fPIC -L/usr/lib/x86_64-linux-gnu\ -lboost_filesystem -lboost_thread -lboost_serialization -lboost_python -lboost_system UO_STR.o: g++ -c UO_STR.h -o UO_STR.o -I/usr/include/boost \ # -lboost_serialization UO_BaseFun.o:UO_STR.o g++ -c UO_BaseFun.h -o UO_BaseFun.o -I/usr/include/boost \ # -lboost_system -lboost_filesystem -lboost_thread -lboost_serialization UO_libdll_py_wrap.o:UO_BaseFun.o g++ -c UO_libdll_py_wrap.cpp -o UO_libdll_py_wrap.o -fPIC -I/usr/include/python2.7 # -lboost_serialization clean: rm -rf UO_STR.o O_libdll_py_wrap.o UO_BaseFun.o rm -rf UO_BaseFun.so
验证
UO_StoreSystem_py.py:
import UO_BaseFun test = UO_BaseFun.UO_C_Socket() test.StartSocketClient("127.0.0.1",4121)
总结:
相关推荐
mcvsyy 2020-06-27
cyhgogogo 2020-01-02
ice00 2011-06-24
zhangpan 2019-09-06
leeknives 2019-03-20
晓杰0 2019-06-28
chanai 2012-07-06
zhoujk00 2013-02-20
liuhangtiant 2012-12-18
achiverhai 2016-04-15
wangpanyang 2015-12-28
yogoma 2019-02-27
xjd0 2015-08-30
TJaney 2015-08-14
86622317 2011-08-23
xinyupan 2011-04-19
NoobZhou 2010-03-26
iOampDagWatu 2010-03-26