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確實很好,很強大!!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.