如何从PyObject str获取字符字符串?

2024-05-28 23:32:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何在C++中使用Python,并且我想知道如何将返回的Python值转换成我可以在C++中使用的东西。p>

这是我的密码:


    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

Tags: ifsystrackpyrunelsepyobjectstdcout
1条回答
网友
1楼 · 发布于 2024-05-28 23:32:27

您可以使用第UTF-8 Codecs节中的函数

例如,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;

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.

相关问题 更多 >

    热门问题