py.cpp
#include"python2.6/Python.h"
#include
int main()
{
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule = PyImport_ImportModule("hello");//这里是要调用的文件名
PyObject * pClass= PyObject_GetAttrString(pModule, "TestClass");//这里是要调用的函数名
if(!pClass)
{
printf("cannot find class\n");
return -1;
}
PyObject * pTuple = PyTuple_New(1);
PyTuple_SetItem(pTuple, 0, Py_BuildValue("s", "jacky"));
PyObject * pObject = PyEval_CallObject(pClass, pTuple);
pFunc = PyObject_GetAttrString(pObject, "printName");//gdb调试发现错误出现在这一行
PyEval_CallObject(pFunc, NULL);//调用函数
Py_Finalize();//调用Py_Finalize,这个根Py_Initialize相对应的。
return 0;
}
hello.py
class TestClass:
def _init_(self, name):
self.name = name
def printName(self):
print self.name