Pickling routines accessible through the C API?

痞子三分冷 提交于 2019-12-25 04:28:31

问题


I would like to call Python's pickling routines (dumps and loads) from within c++ code. Are they exposed in the official API? I am currently calling those via boost::python from c++, looking for a simpler way perhaps.


回答1:


You can call any Python code through the C API:

static PyObject *module = NULL;
PyObject *pickle;

if (module == NULL &&
    (module = PyImport_ImportModuleNoBlock("pickle")) == NULL)
    return NULL;

now, you can either call it like:

python-2.x

pickle = PyObject_CallMethodObjArgs(module,
                                    PyString_AS_STRING("dumps"),
                                    py_object_to_dump,
                                    NULL);

python-3.x

pickle = PyObject_CallMethodObjArgs(module,
                                    PyUnicode_FromString("dumps"),
                                    py_object_to_dump,
                                    NULL);

or like:

picle = PyObject_CallMethod(module, "dumps", "O", py_object_to_dump);

and then do the error checking and clean up:

if (pickle != NULL) { ... }
Py_XDECREF(pickle);

but in the case of pickle you can just use the cPickle functions directly. The only problem there is that the cPickle module (or _pickle in Python 3) is statically compiled into the Python binary, or needs to be loaded separately. Using the Python import mechanisms is simply easier here.



来源:https://stackoverflow.com/questions/28693433/pickling-routines-accessible-through-the-c-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!