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