51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

C++ 调用 Python 对象

#include <Python.h>
#include <iostream>
using namespace std;


int main()
{	
	// 设置 Python Home 路径,否则找不到 Python 解释器
	Py_SetPythonHome(L"C:\\Users\\china\\miniconda3\\envs\\common-env");


	// 初始化 Python 模块
	Py_Initialize();
	cout << "初始化:" << Py_IsInitialized() << endl;

	// 读取 Python 模块
	// PyObject* pModule = PyImport_Import(PyUnicode_FromString("hello"));
	PyObject* pModule = PyImport_ImportModule("hello");
	cout << "pModule:" << pModule << endl;

	// 调用方式一
	PyObject* pFuncMyPow = PyObject_GetAttrString(pModule, "my_pow");
	cout << "pFunc:" << pFuncMyPow << endl;

	if (!PyCallable_Check(pFuncMyPow))
	{
		return -1;
	}

#if 1
	PyObject* pArgs = PyTuple_New(2);
	cout << "pArgs:" << pArgs << endl;
	PyTuple_SetItem(pArgs, 0, PyLong_FromLong(2));
	PyTuple_SetItem(pArgs, 1, PyLong_FromLong(4));

#else
	PyObject* pArgs = Py_BuildValue("(ii)", 2, 3);
#endif
	
	
	PyObject* pRet = PyObject_CallObject(pFuncMyPow, pArgs);
	if (pRet != nullptr)
	{
		double result = PyFloat_AsDouble(pRet);
		cout << "result1:" << typeid(result).name() << " " << result << " " << pRet << endl;
	}

	// 调用方式二
	pRet = PyObject_CallFunction(pFuncMyPow, "ii", 2, 4);
	if (pRet != nullptr)
	{
		double result = PyFloat_AsDouble(pRet);
		cout << "result2:" << typeid(result).name() << " " << result << " " << pRet << endl;
	}

	// 调用方式三
	pArgs = Py_BuildValue("(ii)", 2, 3);
	// PyObject* pResult = PyObject_CallFunctionObjArgs(pFuncMyPow, pArgs, NULL);
	PyObject* pResult = PyObject_CallFunctionObjArgs(pFuncMyPow, PyLong_FromLong(2), PyLong_FromLong(3), NULL);
	if (pRet != nullptr)
	{
		double result = PyFloat_AsDouble(pRet);
		cout << "result3:" << typeid(result).name() << " " << result << " " << pRet << endl;
	}


	// 调用对象函数
	PyObject* pPerson = PyObject_GetAttrString(pModule, "Person");
	PyObject* person = PyObject_CallObject(pPerson, Py_BuildValue("(si)", "Smith", 18));
	cout << "person:" << person << endl;

	pRet = PyObject_CallMethod(pPerson, "show", "s", "Hello");
	if (pRet != nullptr)
	{
		double result = PyLong_AsLong(pRet);
		cout << "result4:" << typeid(result).name() << " " << result << " " << pRet << endl;
	}


	// 调用另外一个函数
	PyObject* pFuncMyList= PyObject_GetAttrString(pModule, "my_list");
	pRet = PyObject_CallObject(pFuncMyList, nullptr);
	cout << "pFuncMyList:" << PyList_Check(pRet) << endl;
	cout << "pFuncMyList:" << PyList_Size(pRet) << endl;

	PyObject* sub_list = PyList_GetItem(pRet, 1);
	for (int i = 0; i < PyList_Size(sub_list); ++i) {
		PyObject* val = PyList_GetItem(sub_list, i);
		cout << PyLong_AsLong(val) << endl;
	}



	// 清理资源
	Py_DECREF(pRet);
	Py_DECREF(pArgs);
	Py_DECREF(pFuncMyPow);
	Py_DECREF(pModule);

	Py_Finalize();
	cout << "初始化:" << Py_IsInitialized() << endl;


	return 0;
}
赞(0)
未经允许不得转载:工具盒子 » C++ 调用 Python 对象