Python C API:字典解析不正确

2024-09-26 18:13:22 发布

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

我从C执行Python函数。函数返回字典,我希望将其映射到C++映射。你知道吗

当我调用PyObject\u Str时,我得到了字典的完美字符串表示。然而,PyDict\u Check说这不是一本字典:

        // Call the function
    PyObject* args = PyTuple_Pack(1,PyString_FromString((const char *) blob_pointer)); // argument is irrelevant for the question
    PyObject *dict = PyObject_CallObject(serialize_func, args);
    Py_DecRef(args);

    // THIS PRINTS A DICT!?!
    std::cout << PyString_AsString(PyObject_Str(dict)) << std::endl;

    //Nope
    if (dict == NULL) {
        std::cout << "Return value was null!" << std::endl;
        PyErr_Print();
    }

    std::cout << "Called python function" << std::endl;

    // Returns false!
    if (!PyDict_Check(dict)) {
        PyErr_Print();
        std::cout << "serialized value was not a dict" << std::endl;
        Py_DecRef(dict);
        return true;
    }

输出:

{...} // The expected dictionary
Called python function
serialized value was not a dict
Done.

为什么会这样?是pythoncapi中的bug还是我遗漏了什么?你知道吗

python版本是2.7.13。你知道吗

编辑

最后,我使用了一个难看的解决方法来获取字符串表示并从中构建一个c++映射。我仍然想知道为什么代码会这样做。你知道吗


Tags: 函数字符串字典valuecheckargsfunctiondict

热门问题