C/C++和Python的交互

13 篇文章 0 订阅
11 篇文章 0 订阅

http://blog.sina.com.cn/s/blog_67ac78cf01010sjk.html

#测试脚本

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

// pytest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Python.h>

int main(int argc, char* argv[])
{
//初始化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'");

//引入模块
pModule = PyImport_ImportModule("test_code");
//获取模块字典属性
pDict = PyModule_GetDict(pModule);

//直接获取模块中的函数
pFunc = PyObject_GetAttrString(pModule, "hello");

//参数类型转换,传递一个字符串。将c/c++类型的字符串转换为python类型,元组中的python类型查看python文档
pArg = Py_BuildValue("(s)", "hello charity");

//调用直接获得的函数,并传递参数
PyEval_CallObject(pFunc, pArg);

//从字典属性中获取函数
pFunc = PyDict_GetItemString(pDict, "arg");
//参数类型转换,传递两个整型参数
pArg = Py_BuildValue("(i, i)", 1, 2);

//调用函数,并得到python类型的返回值
result = PyEval_CallObject(pFunc, pArg);
//c用来保存c/c++类型的返回值
int c;
//将python类型的返回值转换为c/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)", "charity");
//输出返回值
char* name=NULL;
PyArg_Parse(result, "s", &name);
printf("%s\n", name);

PyRun_SimpleString("print 'python end'");

//释放python
Py_Finalize();
getchar();
return 0;
}

运行结果:
python start
hello world
hello charity
a= 1
b= 2
a+b=3
init
hello, charity
charity
python end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值