[英]C-API from Python - How can I get a string?
Euler Math Toolbox ( www.euler-math-toolbox.de ) has an interface with Python 2. Now it should interface with Python 3. But I seem to be unable to read output from Python. Euler Math Toolbox ( www.euler-math-toolbox.de ) has an interface with Python 2. Now it should interface with Python 3. But I seem to be unable to read output from Python. Below is a simple example of what I am trying to do.下面是我正在尝试做的一个简单示例。 The code fails in the last step, PyBytes_AsString().代码在最后一步 PyBytes_AsString() 中失败。 Probably, I am completely off track here.可能,我在这里完全偏离了轨道。
Please advice.请指教。
#include <stdio.h>
#include <Python.h>
const char* pystart = "t = \"test\"";
int main()
{
printf("Test Programm for Python 3.8\n");
Py_Initialize();
PyObject* pModule = PyImport_AddModule("__main__"); //create main module
if (!pModule)
{
printf("Could not create main module in Python.");
return 0;
}
if (PyRun_SimpleString(pystart) == -1)
{
printf("Could not run pystart.");
return 0;
}
PyObject* t = PyObject_GetAttrString(pModule, "t");
if (!t)
{
printf("Could not get t.");
return 0;
}
char* out = PyBytes_AsString(t);
if (!out)
{
printf("Could not get the string.");
return 0;
}
printf(out);
return 1;
}
The trick is, of course, to convert from unicode with PyUnicode_AsEncodedString(t,"utf-8","strict") before applying PyBytes_AsString().当然,诀窍是在应用 PyBytes_AsString() 之前使用 PyUnicode_AsEncodedString(t,"utf-8","strict") 从 unicode 转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.