include "Python.h";
每个模块函数的包装函数,即:PyObject* Module_func();
模块函数与包装函数的映射表,即:PyMethodDef ModuleMethods[]对应表;
模块的初始化函数:void initModule()部分。
int add(int x,int y)
{
}
include "Python.h";
extern int add(int);
PyObject *add_wrap(PyObject *self, PyObject *args)
{
}
参数说明:
调用完add后,我们需要返回结果。这个结果是c的type或者是我们自己定义的类型。必须把它转换成PyObject,让python认识。这个用Py_BuildValue来完成。它是PyArg_ParseTuple的逆过程。他的第一个参数和PyArg_ParseTuple的第二个参数一样,是个格式化符号。第二个参数是我们需要转换的参数。Py_BuildValue会把所有的返回值组装成一个tutple给python。
static PyMethodDef TestModelMethods[] =
{
};
void initTestModel(void)
{
}
这样python在导入TestModel的模块时候,才会找到initTestModel()这个函数,并调用。这个函数调用Py_InitModule来将模块名字和映射表结合在一起。
他表示,TestModel这个模块使用TestModelMethods这个映射表。python应该这样导入我们的module的.然后我们可以将生成的模块导入到Python环境中,并调用其中的函数。
2. 怎样用SWIG生成C的wraper
(1) 写源程序;
(2) 写后缀为.i的脚本文件;
(3) 使用命令"swig -python TestModel.i"生成TestModel_wrap.c,example_wrap.doc;
(4) 编译连接成共享库。
%module TestModel
%{
#include "TestModel.h"
%}
extern int add(int);
3. 用SWIG生成C++的wraper
(1) 写.cpp源程序;
(2) 写.i脚本文件;
(3) swig -c++ -python foo.i
生成TestModel_wrap.c,TestModel_wrap.doc;
(4) 编译连接成共享库TestModel.so。
则生成Python的foo模块,可以通过调入foo模块使用其中的类成员函数、成员变量。
class TestModel
{
public:
#include "TestModel.h"
TestModel::TestModel()
{
}
int TestModel::add(int x,int y)
{
}
为之写TestModel.i文件:
%module TestModel
%{
#include "TestModel.h"
%}
class TestModel
{
public:
};
编译方式:
(1.控制台方式)
(2.编辑器方式)
在.net编辑器里选中.i文件,然后在属性里进行设置:
命令行:
..\SDK\swigwin\swig
输出:$(InputDir)$(InputName)_wrap.cxx
并且在工程属性里要指定python库的相关文件,包括include和libs。
最后,进行编译得到*.cxx文件,然后将该文件添加到工程重新进行编译。
#include <iostream>
#include <string>
#include "TestModel_wrap.cxx"
int main() {
}