《人生苦短,我用python·七》各种报错问题解决及C++调用python的接口

1、VS的debug版本正常可以调用python的release版本(python安装完只有release版本的dll和lib),在项目——附加依赖项中加入python39.lib然后编译debug版本报错,无法打开python39_d.lib,我在项目属性配置的是调用release版本的库为啥调用了debug版本,点开python.h头文件进入pyconfig.h头文件,发现在debug模式下python的debug版本高亮,可能在项目属性里定义了宏_DEBUG,这就导致虽然debug项目属性配置了调用release版本的python,但这个宏导致还是调用debug版本的python
在这里插入图片描述
现在测试把#include<python.h>放在pybind11头文件面前在debug版本下这里_DEBUG会高亮,如果把python.h放在pybind11头文件后面在debug版本下_DEBUG不会高亮

2、通过命令可以正常import numpy,但通过C++调用python导入numpy报错:
PyRun_SimpleString(“import numpy”);

Original error was: No module named ‘numpy.core._multiarray_umath’
目前还不知道啥原因,但知道这是调用debug版本的python导致的,目前的解决方案是把VS的附加库目录python38_d.lib换成release版本的python39.lib

3、通过C++调用python中的函数

Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('D:/gen2Plugin/pythonRecipeTest')");//这一步很重要,设置.py文件的路径
导入python模块,是文件名
pModule= PyImport ImportModule("test1”);
if (!pModule){
	PyErr_Print();
	throw std::runtime_error("Failed to load completion module");
}

//从导入的模块中获取python端函数
pFunc = PyObject_GetAttrString(pModule, "getFunc");
if(!pFunc || !PyCallable_Check(pFunc)) {
	PyErr_Print();
	Py_XDECREF(pFunc);
	Py_DECREF (pModule);
	throw std::runtime_error("Failed to load get completions function");
}

//绐python中的函数传参
PyObject* pArgs = PyTuple_Pack(1, PyUnicode_FromString("John")); // Example argument: "John'
if(!pArgs){
	PyErr_Print();
	Py_DECREF(pFunc);
	Py_DECREF(pModule);
	throw std::runtime_error("Failed to create arguments");
}
//从python函数获取返回结果
PyObject* pValue =PyObject Call0bject(pFunc, pArgs);
Py_DECREF(pArgs);
if(pValue){
	// Convert Python object to C string and print result
	const char* result = PyUnicode_AsUTF8(pValue);
	std::cout<<"Python function returned: "<< result<< std::endl;
	Py_DECREF(pValue);
}
else {
	PyErr_Print();
}

Py_Finalize();

碰到一个巨坑的问题:python脚本名字不能为test.py,不然在导入脚本的中函数时 pFunc = PyObject_GetAttrString(pModule, “getFunc”);报错:module ‘test’ has no attribute ‘getFunc’,具体原因还不清楚
如果PyImport_ImportModule和PyObject_GetAttrString报错就换文件名或函数名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦回阑珊

一毛不嫌多,一分也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值