[英]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.