vs c++调用python函数

1.环境配置




2.引用代码

#include <windows.h>
#include "Python.h"
int sppfeature(string str)
{
	Py_SetPythonHome("C:\\Python27\\");
	Py_Initialize();//初始化
	if (!Py_IsInitialized())
	{
		printf("初始化失败!");
		return -1;
	}
	int val = 0;
	PyObject * pModule = NULL;
	PyObject * pFunc = NULL;
	PyObject * pName = PyString_FromString("exfeature");//载入exfeature.py文件
	pModule = PyImport_Import(pName);
	//pModule = PyImport_ImportModule("exfeature");//Test001:Python文件名
	if (!pModule)
	{
		printf("can't find exfeature.py");
		getchar();
		return -1;
	}
	PyObject *pDict = PyModule_GetDict(pModule);
	if (!pDict)
	{
		return -1;
	}
	pFunc = PyDict_GetItemString(pDict, "exfeatofimg");//提取exfeatofimg函数
	//pFunc = PyObject_GetAttrString(pModule, "exfeatofimg");//Add:Python文件中的函数名
	//创建参数:
	PyObject *pArgs = PyTuple_New(1);//函数调用的参数传递均是以元组的形式打包的,1表示参数个数
	char *ustr = G2U(str.c_str()); //由于vs采用GB2312编码,python采用UTF-8,传递的字符串python无法正常解码,需要提前进行转换
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("s", ustr));//0--序号,s表示创建字符串型变量
	PyObject *pReturn = NULL;
	pReturn = PyEval_CallObject(pFunc, pArgs);//调用函数

	int size = PyList_Size(pReturn);//pReturn 为列表  
	//cout << "返回列表的大小为: " << size << endl;
	for (int i = 0; i < size; ++i)
	{
		PyObject *pNewAge = PyList_GetItem(pReturn, i);//相当于 python中的pReturn[i]  
		float newAge;
		PyArg_Parse(pNewAge, "f", &newAge);//将python的值转为c的值
		int v = (newAge > 0) ? 1 : 0;
		val |= (v<<i);
	}

	Py_Finalize();
	return val;
}
char* G2U(const char* gb2312)
{
	int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
	len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
	if (wstr) delete[] wstr;
	return str;
}

说明:

exfeature.py文件需要放置在C:\Python27\Lib路径下

参考:

https://www.cnblogs.com/babietongtianta/p/3143900.html

猜你喜欢

转载自blog.csdn.net/liujianying455/article/details/79738942