Pickling routines accessible through the C API?

2019-09-01 06:59发布

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条回答
你好瞎i
2楼-- · 2019-09-01 07:05

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:

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

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.

查看更多
登录 后发表回答