python與C++的互操作
來源:互聯網
上載者:User
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確實很好,很強大!!!