【发布时间】:2020-06-04 10:07:37
【问题描述】:
我正在用 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
【问题讨论】:
标签: python c++ python-3.x visual-studio-2019 python-c-api