可通过C API访问酸洗程序吗? [英] Pickling routines accessible through the C API?

查看:64
本文介绍了可通过C API访问酸洗程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从c ++代码中调用Python的酸洗例程(dumpsloads).它们在官方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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆