Python Forum
C-API for Python 3 - Get String from Object - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: C-API for Python 3 - Get String from Object (/thread-27801.html)



C-API for Python 3 - Get String from Object - mga010 - Jun-22-2020

I try to read a string from a python object in the C-API but seem to be incapable to find the documentation on how to do that properly in Python 3. The problem could be Unicode or any other issue I am not aware of. I had a solution for Python 2.

So what is wrong with the following code? It fails in the last step with out==0.

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



RE: C-API for Python 3 - Get String from Object - Gribouillis - Jun-22-2020

With your code, the object t will not be a bytes object but a str object, that's why PyBytes_AsString fails and return NULL. You could replace pystart with
pystart = "t = b\"test\"";



RE: C-API for Python 3 - Get String from Object - mga010 - Jun-23-2020

(Jun-22-2020, 04:12 PM)Gribouillis Wrote: With your code, the object t will not be a bytes object but a str object, that's why PyBytes_AsString fails and return NULL. You could replace pystart with
pystart = "t = b\"test\"";

That does indeed work, I tried it. Unfortunately, I cannot use this in the program I am developing. I need to get the content of a Python string via C.

I found the solution now. You have to actively convert with PyUnicode_AsEncodedString before applying PyBytes_AsString. I finally found that in the docs.