c++调用python(笔记)

本文介绍了一个使用C++调用Python代码的例子,演示了如何初始化Python环境、导入模块、调用函数并处理返回结果的过程。具体步骤包括:初始化Python环境、加载Python模块、获取模块中的函数、构造函数参数、调用Python函数并解析返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class PythonManager{
public:
PythonManager();
~PythonManager();


void init();
private:
};
PythonManager::PythonManager(){
Py_Initialize();
init();
}
PythonManager::~PythonManager(){
try{
Py_Finalize();
}
catch (...){
cout << "exception is inPythonManager" << endl;
}
}
void PythonManager::init(){
PyObject* pModule = NULL;
PyObject* pFunc = NULL;
PyObject*pRtn = NULL;
//加载相关模块
PyRun_SimpleString("import sys");  //用于执行python语句
PyRun_SimpleString("sys.path.append('./')");
//PyRun_SimpleString("sys.path.append('./test_py/')"); 
//PyObject* pModule = PyImport_ImportModule("p_one");
//等价于下面这一句
PyObject* pModule = PyImport_ImportModule("test_py.p_one");
PyObject* pFunc = PyObject_GetAttrString(pModule, "add");
PyObject*pArgs = Py_BuildValue("i", 1, 3);
PyObject*pRtn = PyEval_CallObject(pFunc, pArgs);
int rtn = -1;
PyArg_Parse(pRtn, "i",&rtn);  //"i" 表示整型
                             //解析返回的参数。如果是返回 字符串时,不知为何 为空了???
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值