0
0

C++与Python的混合编程-C++调用Python

郑 纪 发表于 2013年06月08日 09:59 | Hits: 9407
Tag: C | python | 编程语言

python的开发效率之高是毋庸置疑的,C++/C的语言性能之快也是让人羡慕的。这一次,鱼和熊掌是可以兼得的 :),混合编程,使得我们可以取之所长,游走在C与python之间。很多游戏开发中使用python来实现战斗脚本。

//1.初始化调用
Py_Initialize();

//2.一般都是通过(pmod = PyImport_ImportModule ("zhengji.app_context")先来
//加载一个模块(py脚本),得到一个PyObject *pmod对象,失败返回NULL类型
2.PyObject* PyImport_ImportModule (char *name)

//3.获取某个方法或者类,PyObject * o是pmod
PyObject* PyObject_GetAttrString (PyObject *o, char *attr_name)

//4.调用该方法 callable_object是第二步返回的指针
PyObject* PyObject_CallFunction (PyObject *callable_object, char *format, ...)

//5.将PyObject* 返回char*
char* PyString_AsString (PyObject *string)

//6.结束初始化
Py_Finalize();

下面是script.py的内容

#!/usr/bin/python
# Filename: script.py
class Student:
    def SetName(self,name):
        self._name = name
    def PrintName(self):
        print self._name
def hello():
    print "Hello World\n"
def world(name):
    print "name"

C++调用Script.py

#include <python2.7/Python.h>
#include <iostream>
#include <string>

int main () {

    //使用python之前,要调用Py_Initialize();这个函数进行初始化
    Py_Initialize();

    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");

    PyObject * pModule = NULL;
    PyObject * pFunc = NULL;
    PyObject * pClass = NULL;
    PyObject * pInstance = NULL;

    //这里是要调用的文件名
    pModule = PyImport_ImportModule("script");
    //这里是要调用的函数名
    pFunc= PyObject_GetAttrString(pModule, "hello");
    //调用函数
    PyEval_CallObject(pFunc, NULL);
    Py_DECREF(pFunc);  

    pFunc = PyObject_GetAttrString(pModule, "world");
    PyObject_CallFunction(pFunc, "s", "zhengji");
    Py_DECREF(pFunc);  

    //测试调用python的类
    pClass = PyObject_GetAttrString(pModule, "Student");
    if (!pClass) {
        printf("Can't find Student class.\n");
        return -1;
    }
    pInstance = PyInstance_New(pClass, NULL, NULL);
    if (!pInstance) {
        printf("Can't create Student instance.\n");
        return -1;
    }
    PyObject_CallMethod(pInstance, "SetName", "s","my family");
    PyObject_CallMethod(pInstance, "PrintName",NULL,NULL);
    //调用Py_Finalize,这个根Py_Initialize相对应的。
    Py_Finalize();
    return 0;
}

编译C++代码

 g++ zj.cpp -o zj -lpython2.7 

输出结果

zj@hp:~/tmp/CcalPy$ ./zj
Hello World
name
my family

原文链接: http://innerbrilliant.sinaapp.com/?p=502

0     0

评价列表(0)