Loading python pickled object in C

别等时光非礼了梦想. 提交于 2021-02-08 05:45:36

问题


I know pickles can be easily loaded into python using

import pickle
p = pickle.load(open("file.pkl"))

I was wondering how to load the same pickle file in pyx/C code in python? I couldn't find the method to directly load it.

Perhaps a solution would be to load in python and pass reference to object in C?


回答1:


The easy answer would be to just compile your code with Cython. Everything there will be done automatically.

In context of the Python C API, you could easily replicate this code with something like:

PyObject *file = NULL, *p = NULL;
PyObject *pickle = PyImport_ImportModule("pickle"); // import module
if (!pickle) goto error;
file = PyFile_FromString("file.pkl", "r"); // open("file.pkl")
if (!pickle) goto error;
p = PyObject_CallMethod(pickle, "load", "O", file); // pickle.load(file)
error:
Py_XDECREF(pickle);
Py_XDECREF(file);

This is done for Python 2, while for Python 3 open("file.pkl") needs to be implemented by using the io module.



来源:https://stackoverflow.com/questions/35768773/loading-python-pickled-object-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!