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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值