`
yuanlanxiaup
  • 浏览: 855738 次
文章分类
社区版块
存档分类
最新评论

python与C++的互操作

 
阅读更多
python中使用c++的模块,讲c++的动态链接库文件直接import进来就可以了。在windows下需要将dll文件扩展名修改为.pyd。在linux/unix下直接使用.so就可以了。 c++编写的python的模块都是动态链接库文件。这是在windows下变使用普通函数编写的关键代码: static PyObject *ge(PyObject * self, PyObject * args){ std::string sts; sts = "help me"; return Py_BuildValue("s", sts.c_str() );}//这是处理函数static PyMethodDef allmehod[]={ {"ge", ge, METH_VARARGS}, {NULL, NULL} };//将函数对应给一个python方法#ifdef BUILD_DLL #define DLL_EXPORT __declspec(dllexport)#else #define DLL_EXPORT __declspec(dllimport)#endifextern "C"DLL_EXPORT void initpyt(){ PyObject *m, *d; m = Py_InitModule("pyt", allmehod); d = PyModule_GetDict(m);}//建立函数字典,暴露函数在windows下面由于PE结构的问题编写动态连接库真的不是太舒服。不过在linux下就好多了,不需要导入导出的处理了,呵呵。 不过c++的准标准库中的boost::python库,更进一步的优化了这一过程。#include<string>#include <boost/python.hpp>using namespace boost::python;#pragma comment(lib, "boost_python.lib")//这里在windows将boost_python.lib链接进来,在linux下去掉这一句在链接时加入静态库boost_python.a的路径就可以了std::string strtmp;char const* fe(){ strtmp ="返回的数据... : "; return strtmp.c_str();}BOOST_PYTHON_MODULE(ge){ def("fe", fe);}呵呵,boost确实很好,很强大!!!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics