以导出类CObject为例

struct CObject

{

void* m_pData;

PyObject* m_pObj;

void fun(){printf("CObject::fun()");};

};

1,定义一个PY结构

struct PY_CObject

{

PyObject_HEAD;

CObject* obj;

};

2,定义构造、初始化、析构函数

static PyObject* PY_CObject_new(PyTypeObject* type,PyObject*,PyObject*)

{

PY_CObject* self=(PY_CObject*)type->tp_alloc(type,0);

self->obj=NULL;

return self;

}

static int PY_CObject_init(PY_CObject*s,PyObject*,PyObject*)

{

s->obj=new CObject;

s->obj->m_pObj=s;

return 0;

}

static void PY_CObject_dealloc(PY_CObject* s);

{

s->ob_type->tp_free(s);

delete s->obj;

s->obj=NULL;

}

3,定义其它成员函数和函数数组

static PyObject* Py_CObject_fun(PY_CObject* self)

{

self->obj->fun();

return Py_None;

}

static PyMethodDef Py_CObject_Methods[]=

{

{"fun", Py_CObject_fun,METH_NOARGS,"fun"},

{0,0,0,0}

}

4,定义导出结构

PyTypeObject PY_CObject_Type=

{

PyObject_HEAD_INIT(NULL)

0,

"CObject",//tp_name

...

PY_CObject_new,

PY_CObject_int,

PY_CObject_dealloc,

Py_CObject_Methods,

...

}

5,导出

voidPy_CObject_Add()

{

Py_Initialize();

PyObject* pUserModules=Py_InitModule("MyPython", NULL);

if (PyType_Ready(&PY_CObjectType)<0) return;

Py_INCREF(&PY_CObject);

PyModule_AddObject(pUserModules, "CObject", &PY_CObject_Type);

}


这样在py文件里面就可以使用CObject了

/*test.py begin*/

#coding=utf-8

import MyPython

def Start:

    obj=CObject()

    obj.fun()

/*test.py end*/

6,执行test.py

PyObject* pModule=PyImport_ImportModule("test");

PyObject* pFunc=PyObject_GetAttrString(pModule, "Start")

PyEval_CallObject(pFunc,NULL);

这样控制台会打印:CObject::fun()

10-05 06:08