【问题标题】:C-API from Python - How can I get a string?来自 Python 的 C-API - 如何获取字符串?
【发布时间】:2020-10-12 11:21:09
【问题描述】:

Euler Math Toolbox (www.euler-math-toolbox.de) 具有与 Python 2 的接口。现在它应该与 Python 3 接口。但我似乎无法读取 Python 的输出。下面是我正在尝试做的一个简单示例。代码在最后一步 PyBytes_AsString() 中失败。可能,我在这里完全偏离了轨道。

请指教。


#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;
}

【问题讨论】:

    标签: python c-api


    【解决方案1】:

    诀窍当然是在应用 PyBytes_AsString() 之前使用 PyUnicode_AsEncodedString(t,"utf-8","strict") 从 unicode 转换。

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      相关资源
      最近更新 更多