问题
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