C/C++中调用python文件

1.将python27安装目录下include、libs文件夹拷贝至Demo程序目录。

2.Demo项目设置包含Python.h、python27.lib);

  (因为安装python27的时候,python27.dll已经放到C:\Windows\System32下,所以不用拷贝至执行程序目录下。)

  //初始化python

  Py_Initialize();

  //定义python类型的变量

  PyObject  *pModule = NULL;

  PyObject  *pFunc = NULL;

  PyObject  *pArg = NULL;

  PyObject  *result =  NULL;

  PyObject  *pClass = NULL;

  PyObject  *pInstance = NULL;

  PyObject  *pDict = NULL;

  //直接运行python代码

  PyRun_SimpleString("print 'python start'");

  //引入模块(Demo.py)

  pModule = PyImport_ImportModule("Demo");

  1.

  //直接获取模块中的函数

  pFunc = PyObject_GetAttrString(pModule,"hello");

  //Demo.py中hello函数参数是一个元组。传递一个字符串,要先将c/c++类型的字符串转换成元组。

  pArg = Py_BuildValue("(s)","hello xiaochun");

  //调用获得的hello函数,并传递参数

  PyEval_CallObject(pFunc,pArg);

  2.

  //获取模块字典属性

  pDict = PyModule_GetDict(pModule);

  //从字典属性中获取函数

  pFunc = PyDict_GetItemString(pDict,"arg");

  //arg函数参数是两个整型数值组成的元组。

  pArg = Py_BuildValue("(i,i)",1,2);

  //调用arg函数,并得到PyObject类型的返回值

  result = PyEval_CallObject(pFunc,pArg);

  //将PyObject类型的返回值result转换成c/c++类型

  int c;

  PyArg_Parse(result,"i",&c);

  printf("a+b=%d\n",c);

  //通过字典属性获取模块中的类

  pClass = PyDict_GetItemString(pDict,"Test");

  //实例化获取的类

  pInstance = PyInstance_New(pClass,NULL,NULL);

  //调用类的方法

  result = PyObject_CallMethod(pInstance,"say_hello","(s)","xiaochun");

  //输出返回值

  char * name = NULL;

  PyArg_Parse(result,"s",&name);

  printf("%s\n",name);

  

  PyRun_SimpleString("print 'python end'");

  getchar();

  return 0;

Demo.py

  def hello(s):

    print "hello world"
    print s
 
def arg(a, b):
    print 'a=', a
    print 'b=', b
    return a + b
 
class Test:
    def __init__(self):
        print "init"
    def say_hello(self, name):
        print "hello,", name
        return name
 
 
上一篇:Linq to Sql:N层应用中的查询(上) : 返回自定义实体


下一篇:CSS实现DIV水平自适应居中