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.
Many years later, not quite answering the question, and based on Martijn Pieters' answer, here is a drop in replacement for Marshal:
static PyObject * PyPickle=NULL;
static PyObject * pDumps=NULL;
static PyObject * pLoads=NULL;
static void init_pickle()
{
if(!pDumps)
pDumps = PyUnicode_FromString("dumps");
if(!pLoads)
pLoads = PyUnicode_FromString("loads");
if(!PyPickle)
PyPickle = PyImport_ImportModule("pickle");
}
static PyObject *PyPickle_ReadObjectFromString(const char *data, Py_ssize_t len)
{
PyObject *pstr = PyBytes_FromStringAndSize(data, len);
PyObject *ret=NULL;
ret = PyObject_CallMethodOneArg(PyPickle, pLoads, pstr);
Py_XDECREF(pstr);
return ret;
}
static PyObject *PyPickle_WriteObjectToString(PyObject *value, int version)
{
//version currently ignored
return PyObject_CallMethodOneArg(PyPickle, pDumps, value);
}
Perhaps someone will find it useful.