[英]Embedding Python 3.3 in a C++ program while only able to read one line at a time from input
作為暑期實習的一部分,我目前正在為大型程序添加嵌入式Python支持(是的,不能擴展)。 理想情況下,我可以將Python支持保留在單個.DLL中,該.DLL當前包含程序的內部腳本語言,並且是將所述語言與Python集成的最簡單的地方。
但是,由於該程序的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上運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.