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

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

下面是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 
#include 
#include 

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

你可能感兴趣的:(C++与Python的混合编程-C++调用Python)