close

 

 

工作需要, 所以來研究C++搭配Python來做實驗, 這裡簡單紀錄一下程式, 東西不難, 大家就看一下就好。

 




#include 
#include 


#include 


using namespace std;

 

void pythonCleanup() {
	Py_Finalize();
}



bool pythonInit()
{
	bool bSuccess = false;
	Py_Initialize();
	int ret = Py_IsInitialized();
	if (ret == 0) {
		printf("Py_IsInitialized is error.\n");
		return bSuccess;
	}
	PyRun_SimpleString("print('Initialize Python Success from C++ program.')");

	return true;
}
 


PyObject* pythonImportModule(const char* pyDir, const char* name) {
	char tempPath[256] = {};
	sprintf(tempPath, "sys.path.append('%s')", pyDir);
	PyRun_SimpleString("import sys");

	PyRun_SimpleString(tempPath);
	PyRun_SimpleString("print('Current sys.path',sys.path)");
	
	// 引入 module, hello.py
	PyObject* module = PyImport_ImportModule(name);
	if (module == nullptr) {
		PyErr_Print();	// Print stack
		cout << "PyImport_ImportModule 'hello.py' not found" << endl;
		return nullptr;
	}

	return module;
}


int callPythonAdd(PyObject* module, int a, int b) {
	PyObject* pDict = PyModule_GetDict(module);
	if (pDict == nullptr) {
		PyErr_Print();
		printf("PyModule_GetDict error \n");
		return -1;
	}

	// 取得Module裡面的function
	PyObject* addFunc = PyDict_GetItemString(pDict, "add");
	if (addFunc == nullptr) {
		printf("PyDict_GetItemString 'add' not found.\n");
		return -1;
	}

	// 構造python 函數入參, 接收2
	// See =>  https://docs.python.org/zh-cn/3.7/c-api/arg.html?highlight=pyarg_parse#c.PyArg_Parse

	PyObject* pArg = Py_BuildValue("(i,i)", a, b);
	
	// Invoke function, and get python type return value
	PyObject* result = PyEval_CallObject(addFunc, pArg);

	int res= 0;
	PyArg_Parse(result, "i", &res);
	return res;
}


bool callPythonGetName(PyObject* module, std::string firstName, std::string& outName) {
	PyObject* pDict = PyModule_GetDict(module);

	if (pDict == nullptr) {
		PyErr_Print();
		printf("PyModule_GetDict Error\n");
		return false;
	}

	PyObject* addFunc = PyDict_GetItemString(pDict, "get_name");
	if (addFunc == nullptr) {
		printf("PyDict_GetItemString 'add' not found.\n");
		return false;
	}

	PyObject* pArg = Py_BuildValue("(s)", firstName.c_str());


	PyObject* result = PyEval_CallObject(addFunc, pArg);

	char* name = nullptr;
	PyArg_Parse(result, "s", &name);

	char tempStr[256] = {};
	int strLen = strlen(name);
	if (strLen > 256) {
		return false;
	}
	strcpy(tempStr, name);
	outName = tempStr;

	return true;
}



void main()
{
	// 1. Initialize python
	if (!pythonInit())
		return;


	PyRun_SimpleString("print('hello world')");
	PyObject* helloModule = pythonImportModule("../", "hello");
	if (helloModule == nullptr)
		return;

	int result = callPythonAdd(helloModule, 1, 3);
	cout << "1+3 = " << result << endl;

	string fullName;
	callPythonGetName(helloModule, "summer", fullName);
	cout << fullName << endl;

	pythonCleanup();

	system("pause");
	return;
}

 


 

 

 



 
 hello.py


 

def add(a,b):
    return a+b

def get_name(first):
    return "your name is {} Eric".format(first)


 

arrow
arrow
    文章標籤
    C++ C visual studio python
    全站熱搜
    創作者介紹
    創作者 Eric 的頭像
    Eric

    一個小小工程師的心情抒發天地

    Eric 發表在 痞客邦 留言(0) 人氣()