这篇笔记记录用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++(废话)