继前篇《Import Module》(http://blog.csdn.net/xiadasong007/archive/2009/09/02/4512797.aspx),继续分析嵌入部分基础知识。这次不多说,有什么问题记得多查英文资料,国内的这方面知识少
还是来看代码,写完我就睡觉了~
#include "python/python.h"
#include <iostream>
using namespace std;
int main(int argc,char** argv)
{
PyObject *pModule, *pClass,*pStuObj,*pFunc;
Py_Initialize();
////////////////
//载入模块stu.py
pModule = PyImport_ImportModule ("stu");
//从模块中得到类Student
pClass = PyObject_GetAttrString (pModule, "Student");
//生成一个学生对象jack,注意3.1版本必须加上小括号:(s),否则会出错
//PyObject_CallObject和另外一个常用的PyEval_CallObject用法极为相近,请看附录部分详解
PyObject * temp=Py_BuildValue("(s)","jack");
pStuObj = PyObject_CallObject(pClass, temp);
//获得函数对象jack中的成员函数printName,
//这个getattr的意思就是得到当前对象的属性(不要局限于C++中的属性哦)
pFunc= PyObject_GetAttrString (pStuObj, "printName");
//调用函数printName
PyEval_CallObject (pFunc, NULL);
////////////////
Py_Finalize();
return 0;
}
/*
附录:
1:Student类,我发现print后面现在必须加上小括号了,否则会有问题
class Student:
name=""
def __init__(self,name):
self.name=name
def printName(self):
print (self.name)
2:PyObject_CallObject和 PyEval_CallObject不同之处:
可以看出,后者较为直接,而且接受NULL,and does explicit type checks
for args and kwds.
PyObject_CallObject(PyObject *o, PyObject *a)
{
! PyObject *r;
! PyObject *args = a;
!
! if (args == NULL) {
! args = PyTuple_New(0);
! if (args == NULL)
! return NULL;
! }
!
! r = PyEval_CallObject(o, args);
!
! if (args != a) {
! Py_DECREF(args);
! }
!
! return r;
}
PyObject_CallObject(PyObject *o, PyObject *a)
{
! return PyEval_CallObjectWithKeywords(o, a, NULL);
}
*/