c++调用Python问题求解

upbiuGIS upbiuGIS 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
问题描述:
程序执行至调用函数前都没有错误,但返回的结果为空,即pReturn为空。想请教各位这是什么原因?另外,在释放python对象指针代码处,VS2010编译报错(之前灰掉这块了):
“ 无法解析的外部符号 __imp___Py_Dealloc,该符号在函数 _main 中被引用
1>TT.obj : error LNK2019:
无法解析的外部符号 __imp___Py_NegativeRefcount,该符号在函数 _main 中被引用
1>TT.obj : error LNK2001: 无法解析的外部符号 __imp___Py_RefTotal”
请大神指点!以下是代码块。
python代码
```
#-*- coding:gb2312 -*-
def hello(a,b) :
return a+b
```
c++代码
```
#include<iostream>
#include<Python.h>
using namespace std;
int main()
{
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
PyObject * pModule = NULL;//声明变量

PyObject * pFunc = NULL;// 声明变量
PyObject *pDict = NULL;
PyObject *pArgs = NULL;
pModule =PyImport_ImportModule("test_call");//这里是要调用的文件名
if ( !pModule )
{
printf("can't find pytest.py");
getchar();
return -1;
}

pDict = PyModule_GetDict(pModule);
//pFunc= PyObject_GetAttrString(pModule, "hello");//这里是要调用的函数名
pFunc = PyDict_GetItemString(pDict, "hello");

if ( !pFunc || !PyCallable_Check(pFunc) )
{
printf("can't find function [hello]");
getchar();
return -1;
}

pArgs = Py_BuildValue("i",3);
pArgs = Py_BuildValue("i",4);

PyObject *pReturn = NULL;
pReturn = PyEval_CallObject(pFunc, pArgs);//调用函数

if(!pReturn)
{
cout<<"null.\n";
return -1;
}

int result = -1;
if (pReturn && PyArg_ParseTuple(pReturn,"i", &result))
{
cout << "3+4 = " << result << endl;
}

Py_DECREF(pModule);
Py_DECREF(pFunc);
Py_DECREF(pDict);
Py_DECREF(pArgs);

Py_Finalize();//调用Py_Finalize,这个根Py_Initialize相对应的。

return 0;
}
```
...全文
评论 2
收藏 已收藏
分享
返回顶部
upbiuGIS
其它技术问题 3,881 成员 9,044 内容