我目前正在爲一個大型程序添加嵌入式Python支持(是的,擴展不是選項),作爲我夏天的一部分實習。理想情況下,我可以將Python支持保存在一個.DLL文件中,該文件目前包含程序的內部腳本語言,並且是集成所述語言和Python的最簡單的地方。將Python 3.3嵌入到C++程序中,同時只能從輸入中一次讀取一行
但是,由於程序的API,我只有一個輸入函數可供使用。該函數的返回值是當前輸入的一行,可能是控制檯或文件。輸入接口不能(在.DLL中)轉換爲流對象,緩衝區或FILE指針。
我當前的測試代碼(寫的程序之外,使用的std :: string,istream的,和函數getline猿的限制)是
// start python
Py_Initialize();
try
{
cout << "Python " << Py_GetVersion() << endl;
string block;
bool in_block = false;
while (!cin.eof())
{
string str;
cout << (in_block ? "... " : ">>> "); // prompt string
getline(cin,str);
if (in_block) // if in an indented block
{
if (str.front() != ' ' && str.front() != '\t') // if ending the indented block
{
PyRun_SimpleString(block.c_str()); // run Python code contained in block string
block.clear(); // clear string for next block
in_block = false; // no longer in block
}
else // a component of an indented block
{
block += (str+'\n'); // append input to block string
continue; // do not pass block exit code, do not collect two hundred dollars
}
}
// either not in an indented block, or having just come out of one
if (str.back() == ':') // if colon, start new indented block
{
block = (str+'\n');
in_block = true;
continue;
}
else { PyRun_SimpleString(str.c_str()); } // otherwise, run block-free code
}
}
catch (error_already_set e) { PyErr_Print(); }
// close python
Py_Finalize();
// done
return 0;
我還沒有遇到嚴重的問題,這個技巧,但它讓我覺得不合時宜。任何人都可以想出一個更好的方法來做到這一點?
我已經與我的老闆清除了boost.python庫,如果這提供了一些有用的技巧,但沒有我。
編輯:我應該提到程序本身,而不是我微薄的測試牀,必須在MS Windows上運行。
爲了澄清這裏,你是否試圖嵌入一個交互式解釋器外殼? – abarnert