2

Hi i'm learning how to use python in c++ and am wondering how I convert the returned python value to something I can use in c++.

Here's my code:


    CPyInstance pyInstance;
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");
    CPyObject pName = PyUnicode_FromString("Info");
    CPyObject pModule = PyImport_Import(pName);

    if (pModule)
    {
        CPyObject pFunc = PyObject_GetAttrString(pModule, "getTracks");

        if (pFunc && PyCallable_Check(pFunc))
        {
            CPyObject pValue = PyObject_CallObject(pFunc, NULL);
            //print the returned string
        }
        else { std::cout << "Error: function getTracks()\n"; }
    }
    else { std::cout << "error: no module imported"; }

    return 0;
def getTracks():
    
    returnString = ""

    for track in results['tracks'][:10]:
        returnString += 'track    : ' + track['name']
      
    return returnString

1 Answer 1

1

You can use functions from section UTF-8 Codecs.

For example, PyUnicode_AsUTF8AndSize:

CPyObject pValue = PyObject_CallObject(pFunc, NULL);
Py_ssize_t size;
const char* data = PyUnicode_AsUTF8AndSize(pValue.getObject(), &size);
std::cout << std::string(data, size) << std::endl;

Or PyUnicode_AsUTF8

const char* data = PyUnicode_AsUTF8(pValue.getObject());
std::cout << data << std::endl;

const char* PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)

Return a pointer to the UTF-8 encoding of the Unicode object, and store the size of the encoded representation (in bytes) in size. The size argument can be NULL; in this case no size will be stored. The returned buffer always has an extra null byte appended (not included in size), regardless of whether there are any other null code points.

This caches the UTF-8 representation of the string in the Unicode object, and subsequent calls will return a pointer to the same buffer. The caller is not responsible for deallocating the buffer.

[...]

const char* PyUnicode_AsUTF8(PyObject *unicode)

As PyUnicode_AsUTF8AndSize(), but does not store the size.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.