python調C++的方式——2.

這篇筆記記錄用C++編寫Python擴展模塊的方式,以及與C語言編寫Python模塊的幾個需要注意的不同點。

cppExample.cpp

// 簡單的hello world 
#include "cppExample.h"

void CppEasyTest::helloWorld(){
    std::cout << "hello world" << std::endl;
    return;
}

cppExample.h

#include <iostream>
#include <stdio.h>

class CppEasyTest{
    public:
        CppEasyTest(){};
        ~CppEasyTest(){};
        void helloWorld();
};

cppExample_wrap.cpp

#include <Python.h>
#include "cppExample.h"           // @ 1 必須要包含聲明C++類和方法的頭文件


PyObject* wrap_helloWorld(PyObject* self, PyObject* args)
{
    CppEasyTest* pobj = new CppEasyTest();
    pobj->helloWorld();
    delete pobj;
    pobj = NULL;
    return Py_BuildValue("");
}

static PyMethodDef cppExampleMethods[] =
{
    {"helloWorld", wrap_helloWorld, METH_VARARGS, "print hello world"},
    {NULL, NULL}
};

extern "C"{                 // @ 2初始化時,必須要用extern "C" 否則g++編譯器編譯不過
void initcppExample(void)
{
    PyObject* m;
    m = Py_InitModule("cppExample", cppExampleMethods);
}
}

編譯

g++ -fPIC -c -I /usr/include/python2.7/ -I /usr/lib/python2.7/config-x86_64-linux-gnu/ cppExample.cpp cppExample_wrap.cpp
g++ -shared -o cppExample.so cppExample.o cppExample_wrap.o

python測試

import cppExample
if __name__ == "__main__":
  ## @ 2 C++編寫的python模塊
  print cppExample.helloWorld()
  '''
hello world
None
'''

和 C語言編寫Python擴展模塊不同的是:
1.在wrap文件中必須要include包含C++方法的頭文件不然會報錯;
2.初始化方法要extern “C”
3.編譯使用g++(廢話)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章