c++调用python取不出返回值

kaikai_sk kaikai_sk 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
下面是我的c++代码:
/**g++ -o callpy callpy.cpp -I/usr/include/python2.6 -L/usr/lib64/python2.6/config -lpython2.6**/
#include <Python.h>
#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
// 初始化Python
//在使用Python系统前,必须使用Py_Initialize对其
//进行初始化。它会载入Python的内建模块并添加系统路
//径到模块搜索路径中。这个函数没有返回值,检查系统
//是否初始化成功需要使用Py_IsInitialized。
Py_Initialize();

// 检查初始化是否成功
if (!Py_IsInitialized()) {
return -1;
}
// 添加当前路径
//把输入的字符串作为Python代码直接运行,返回0
//表示成功,-1表示有错。大多时候错误都是因为字符串
//中有语法错误。
PyRun_SimpleString("import sys");
PyRun_SimpleString("print '---import sys---'");
PyRun_SimpleString("sys.path.append('./')");
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs,*res;

// 载入名为pytest的脚本
pName = PyString_FromString("myPredict");
pModule = PyImport_Import(pName);
if (!pModule) {
printf("can't find pytest.py");
getchar();
return -1;
}
pDict = PyModule_GetDict(pModule);
if (!pDict) {
return -1;
}

// 找出函数名为add的函数
printf("----------------------\n");
pFunc = PyDict_GetItemString(pDict, "predict");
if (!pFunc || !PyCallable_Check(pFunc)) {
printf("can't find function [add]");
getchar();
return -1;
}

// 参数进栈
pArgs = PyTuple_New(2);

// PyObject* Py_BuildValue(char *format, ...)
// 把C++的变量转换成一个Python对象。当需要从
// C++传递变量到Python时,就会使用这个函数。此函数
// 有点类似C的printf,但格式不同。常用的格式有
// s 表示字符串,
// i 表示整型变量,
// f 表示浮点数,
// O 表示一个Python对象。

PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 8));
PyTuple_SetItem(pArgs, 1, Py_BuildValue("l", 0));

// 调用Python函数
res=PyObject_CallObject(pFunc, pArgs);

int delay=-1;
PyArg_Parse(res, "i", &delay);
cout << delay << endl;

Py_DECREF(pName);
Py_DECREF(pArgs);
Py_DECREF(pModule);

// 关闭Python
Py_Finalize();
return 0;
}

python代码:
from sklearn.externals import joblib
from numpy import *

def predict(count,iotype):
test_X=[]
test_X.append(count)
test_X.append(iotype)
X =[]
X.append(test_X)
clf = joblib.load("train_model.m")
test_Y=clf.predict(X)
print test_X
print X
print test_Y
return test_Y[0]

if __name__=="__main__":
delay=predict(48,1)
print delay

编译环境VS2015
...全文
评论 1
收藏 已收藏
分享
返回顶部
kaikai_sk
其它技术问题 3,881 成员 9,044 内容