这里使用:
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)