C++调用python

Fatal Python error: Py_Initialize: unable to load the file system codec
Py_SetPythonHome(L"D:/python/Python3.5_32");

要把VC环境改成x64
把python的include包,以及libs包添加进来

C++调用python
#include "stdafx.h"
#include <iostream>
using namespace std;

extern "C"
{
#include "Python.h"
}


char* py_call(const char* module, const char* class_name, char* function, char* format, ...)
{
	PyObject* pName = NULL;
	PyObject* pMod = NULL;
	PyObject* pDict = NULL;
	PyObject* pClass = NULL;
	PyObject* pInstance = NULL;
	PyObject* pParam = NULL;
	PyObject* pResult = NULL;
        PyObject* pFunc=NULL;

	// 导入模块
	pName = PyUnicode_FromString(module);
	pMod = PyImport_Import(pName);
	if (!pMod)
	{
		return "";
	}

	// 获取模块字典属性
	pDict = PyModule_GetDict(pMod);
	if (!pDict)
	{
		return "";
	}

	// 通过字典获取模块中的类
	pClass = PyDict_GetItemString(pDict, class_name);
	if (!pClass)
	{
		return "";
	}

	pInstance = PyObject_CallObject(pClass, NULL);
	if (!pInstance)
	{
		return "";
	}

	pResult = PyObject_CallMethod(pInstance, function, format);

	char *rlt_ch = NULL;
	PyArg_Parse(pResult, "s", &rlt_ch);
        pFunc =PyObject_GetAttrString(pMod, "hello");
	PyObject_CallObject(pFunc, NULL);
	return rlt_ch;
}

void init()
{
	Py_Initialize();
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('./')");
}

void finit()
{
	Py_Finalize();
}



int _tmain(int argc, _TCHAR* argv[])
{
	init();
	char* rlt_char = py_call("hello", "power", "liupan", "()");
	finit();
	printf("%s\n", rlt_char);

}

#对应的hello.py文件
import numpy as np
class power():
    def liupan(self):
        return str(np.sum(np.array(1)+np.array(2)))

def hello():
    print('hello')

调用方法(无参数)
pName = PyUnicode_FromString("ModuleOne");
pMod = PyImport_Import(pName);
pFunc = PyObject_GetAttrString(pMod, "PassArrayFromCToPython");
FuncResult = PyObject_CallObject(pFunc, ArgArray);

有两个参数,赋值为1,2
int t[] = {1, 2};
pArgs = PyTuple_New(2);
for (int i = 0; i < 2; i++)
{
pValue=PyLong_FromLong(t[i]);
PyTuple_SetItem(pArgs, i, pValue);
}
FuncResult = PyObject_CallObject(pFunc, pArgs);

转换一维数组
PyObject* tranCArrayToPyObject(double CArray[])
{

	PyObject *PyList = PyList_New(3);
	PyObject *ArgList = PyTuple_New(1);
	for (int Index_i = 0; Index_i < PyList_Size(PyList); Index_i++) {

		PyList_SetItem(PyList, Index_i, PyFloat_FromDouble(CArray[Index_i]));
	}
	PyTuple_SetItem(ArgList, 0, PyList);
	return ArgList;
}

#构建二维数组
	PyObject *PyList = PyList_New(3);
	PyObject *ArgList = PyTuple_New(1);
	for (int i = 0; i < 3; i++)
	{
		PyList_SetItem(PyList, i, tranCArrayToPyObject(CArrays[i]));
	}
	PyTuple_SetItem(ArgList, 0, PyList);

传一维数组出来,直接用List
传入一二维数组array,在Python里先通过np.array(array)[:,0]转成一正常np.array
传多维数组出来,也用list

posted @ 2018-07-05 14:42  blog_hfg  阅读(1013)  评论(0)    收藏  举报