Search code examples
c++python-3.xpython-extensionspython-embedding

Convert std::string to PyObject in C++ in Python3


I am trying to convert std::string to PyObject.

std::string st = jsp.updateRoot(people, people);
PyObject* pValue = PyBytes_AsString(st);

It is not working using the above method.

How can I convert?


Solution

  • From doc.:

    char* PyBytes_AsString(PyObject *o)

    Return a pointer to the contents of o. The pointer refers to the internal buffer of o, which consists of len(o) + 1 bytes. The last byte in the buffer is always null, regardless of whether there are any other null bytes. The data must not be modified in any way, unless the object was just created using PyBytes_FromStringAndSize(NULL, size). It must not be deallocated. If o is not a bytes object at all, PyBytes_AsString() returns NULL and raises TypeError.

    This is the wrong direction in OP's case.

    The function for the opposite conversion is

    PyObject* PyBytes_FromString(const char *v)

    Return value: New reference.

    Return a new bytes object with a copy of the string v as value on success, and NULL on failure. The parameter v must not be NULL; it will not be checked.