C++(MFC)调用Python

环境:

phyton版本:3.10

VS版本:VS2017


包含文件头:Python\Python310\include
包含库文件:Python\Python310\libs

程序运行期间,以下函数只需要调用一次即可,重复调用会导致崩溃
void Initialize();
void Finalize();

“C_Test.py”需要拷贝程序运行所有的目录。

下载:https://download.csdn.net/download/luo_sen/88094131

PythonHelper.h

#pragma once
#include
using namespace std;
/*
phyton版本:3.10
包含文件头:Python\Python310\include
包含库文件:Python\Python310\libs
*/


#define  PYTHON_FILE_NAME _T("C_Test")

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



class CPythonHelper
{
	
public:
	void Initialize();
	void Finalize();
	PyObject* GetPyFunc(char* pModuleName, char* pFuncName);
	PyObject* GetPyFunc(CString strModuleName, CString strFuncName);
	string CStringToPyString(CString text);
	CString PyObjectToCString(PyObject *pPyObj);
	PyObject * RunPyFunc(char* pModuleName, char* pFuncName, PyObject *pArgs);
	PyObject * RunPyFunc(CString strModuleName, CString strFuncName, PyObject *pArgs);
	std::string UTF8_To_string(const std::string & str);
	std::string CPythonHelper::string_To_UTF8(const std::string & str);


	int PyTupleSetItem(PyObject *, Py_ssize_t, PyObject *);

	
};

PythonHelper.cpp

#include "pch.h"
#include "PythonHelper.h"


std::string CPythonHelper::UTF8_To_string(const std::string & str)
{
	int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);

	wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴 
	memset(pwBuf, 0, nwLen * 2 + 2);

	MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);

	int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);

	char * pBuf = new char[nLen + 1];
	memset(pBuf, 0, nLen + 1);

	WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

	std::string retStr = pBuf;

	delete[]pBuf;
	delete[]pwBuf;

	pBuf = NULL;
	pwBuf = NULL;

	return retStr;
}
std::string CPythonHelper::string_To_UTF8(const std::string & str)
{
	int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);

	wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴 
	ZeroMemory(pwBuf, nwLen * 2 + 2);

	::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);

	int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);

	char * pBuf = new char[nLen + 1];
	ZeroMemory(pBuf, nLen + 1);

	::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

	std::string retStr(pBuf);

	delete[]pwBuf;
	delete[]pBuf;

	pwBuf = NULL;
	pBuf = NULL;

	return retStr;
}


string CPythonHelper::CStringToPyString(CString text)
{
	string tt = CT2A(text);
	string strUTF8 = string_To_UTF8(tt);
	return strUTF8;
}

CString CPythonHelper::PyObjectToCString(PyObject *pPyObj)
{
	PyObject* str = PyUnicode_AsEncodedString(pPyObj, "utf-8", "Error");
	char *result = (PyBytes_AsString(str));
	string temp = UTF8_To_string(result);
	CString strResult = CString(temp.c_str());
	return strResult;
}

void CPythonHelper::Initialize()
{
	Py_Initialize();	
}

void CPythonHelper::Finalize()
{
	Py_Finalize();
}
PyObject* CPythonHelper::GetPyFunc(CString strModuleName, CString strFuncName)
{
	string pModuleName = CStringToPyString(strModuleName);
	string pFuncName = CStringToPyString(strFuncName);
	return GetPyFunc((char*)pModuleName.c_str(), (char*)pFuncName.c_str());

}

PyObject* CPythonHelper::GetPyFunc(char* pModuleName, char* pFuncName)
{
	PyObject *pModule = PyImport_ImportModule(pModuleName);
	PyObject *pFunc = PyObject_GetAttrString(pModule, pFuncName);
	return pFunc;
}

PyObject * CPythonHelper::RunPyFunc(char* pModuleName, char* pFuncName, PyObject *pArgs)
{
	PyObject *pFunc = GetPyFunc(pModuleName, pFuncName);
	PyObject *pRetrun = PyObject_CallObject(pFunc, pArgs);
	return pRetrun;
}
PyObject * CPythonHelper::RunPyFunc(CString strModuleName, CString strFuncName, PyObject *pArgs)
{
	string pModuleName = CStringToPyString(strModuleName);
	string pFuncName = CStringToPyString(strFuncName);
	PyObject *pRetrun = RunPyFunc((char*)pModuleName.c_str(), (char*)pFuncName.c_str(), pArgs);
	return pRetrun;
}
int CPythonHelper::PyTupleSetItem(PyObject * pObject, Py_ssize_t index, PyObject * pData)
{
	return PyTuple_SetItem(pObject, index, pData);
}






C_Test.py

def Hello():
    print("hello Python")

def Add(a,b):
    import numpy as np
    print(np.pi)
    return a+b

def GetText(msg):
    print(msg)
    return  msg;

程序调用示例(一):

CPythonHelper PY;

PY.Initialize();

    int a = 10;
	int b = 20;
	int sum = 0;	
	//参数设置
	PyObject *pArgs = PyTuple_New(2);
	PY.PyTupleSetItem(pArgs, 0,Py_BuildValue("i", a));
	PY.PyTupleSetItem(pArgs, 1, Py_BuildValue("i", b));
	//调用函数
	PyObject *pRetrun = PY.RunPyFunc(PYTHON_FILE_NAME, _T("Add"), pArgs);
	//返回值转换
	PyArg_Parse(pRetrun, "i", &sum);
	//输出
	CString strResult = _T("");
	strResult.Format(_T("%d+%d=%d"), a, b, sum);
	AfxMessageBox(strResult);

PY.Finalize();

程序调用示例(二)

  CPythonHelper PY;
  PY.Initialize();
    CString strText = _T("ABC中国人123");
	//参数设置
	PyObject *pArgs = PyTuple_New(1);
	PY.PyTupleSetItem(pArgs, 0, Py_BuildValue("s", PY.CStringToPyString(strText).c_str()));
	//调用函数
	PyObject *pRetrun = PY.RunPyFunc(PYTHON_FILE_NAME, _T("GetText"), pArgs);
	//返回值转换
	CString strResult = PY.PyObjectToCString(pRetrun);
	//输出
	AfxMessageBox(strResult);
 PY.Finalize();

你可能感兴趣的:(mfc,python,c++,中文)