酸洗例程可通过 C API 访问? [英] Pickling routines accessible through the C API?
问题描述
我想从 C++ 代码中调用 Python 的酸洗例程(dumps
和 loads
).它们是否在官方 API 中公开?我目前正在通过 c++ 中的 boost::python 调用这些方法,也许正在寻找一种更简单的方法.
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.
推荐答案
您可以通过 C API 调用任何 Python 代码:
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);
或喜欢:
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);
但在 pickle
的情况下,您可以只使用 cPickle
函数 直接.唯一的问题是 cPickle
模块(或 Python 3 中的 _pickle
)被静态编译成 Python 二进制文件,或者需要单独加载.在这里使用 Python 导入机制更容易.
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.
这篇关于酸洗例程可通过 C API 访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!