我正在用C ++写一个base64函数。我想用python进行编码并将结果返回到我的c ++程序。这是我的代码:
string EncodeBase64(string str)
{
Py_Initialize();
PyObject* ret1 = NULL;
PyObject* ret2 = NULL;
PyObject* main = PyImport_AddModule("__main__");
PyObject* _g = PyModule_GetDict(main);
PyObject* _l = PyDict_New();
string py = "str(base64.b64encode('" + str + "'.encode('utf-8')), 'utf-8')";
string pyb = "base64.b64encode('" + str + "'.encode('utf-8'))";
char* rec = new char[8192];
cout << "Request 1: " << py << endl;
cout << "Request 2: " << pyb << endl;
PyRun_SimpleString("import base64");
ret1 = PyRun_String(py.c_str(), Py_file_input, _g, _l);
main = PyImport_AddModule("__main__");
_g = PyModule_GetDict(main);
_l = PyDict_New();
ret2 = PyRun_String(pyb.c_str(), Py_file_input, _g, _l);
if (!ret1)
{
cout << "Can not get return value 1." << endl;
}
else
{
cout << "Type of Return Value 1: " << ret1->ob_type->tp_name << endl;
}
if (!ret2)
{
cout << "Can not get return value 1." << endl;
}
else
{
cout << "Type of Return Value 2: " << ret1->ob_type->tp_name << endl;
}
Py_Finalize();
return "";
}
我输入了字符串“ 123456”,程序输出了这个:
Request 1: str(base64.b64encode('123456'.encode('utf-8')), 'utf-8')
Request 2: base64.b64encode('123456'.encode('utf-8'))
Type of Return Value 1: NoneType
Type of Return Value 2: NoneType
我尝试将请求字符串输入到python,运行正常。结果如下:
C:\Users\15819>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> str(base64.b64encode('123456'.encode('utf-8')), 'utf-8')
'MTIzNDU2'
>>> base64.b64encode('123456'.encode('utf-8'))
b'MTIzNDU2'
我想知道为什么PyRun_String
的返回值是NoneType
,以及如何使它返回正确的值。我的环境信息:
System: Windows 10 1909 x64
C++IDE: Visual Studio 2019 Professional
Python version: 3.7.4
Project Config: Release X64
将start
的Py_file_input
参数传递实际上类似于将Py_file_input
传递给'exec'
;这意味着要像将其作为一个完整的模块一样运行(想像它要的是the compile
built-in的“结果”;没有“结果”)。
仅表达式的计算结果为非平凡/非compile
的结果,而不是模块或语句,因此对于除import modulename
以外的任何None
参数(对于start
等于Py_eval_input
模式),结果将为始终为Py_eval_input
(仅是'eval'
,因为他们需要返回某些内容来区分compile
是失败还是成功),并且None
模式需要返回None
而不是布尔值)。如果要计算表达式并获取结果,则必须为NULL
参数使用eval
。