python:腌制c对象 [英] python: pickling c objects
问题描述
首先,我不希望有解决方案,只是希望获得一些有关如何开始的指导.
First off I'm not expecting a solution, just hoping for some pointers on how to start.
我有一个带有嵌入式Python解释器的C程序.程序用作输入的Python脚本显然引用了C定义的对象和函数.我现在想使其中一些对象可腌制.
I've got a C program with an embedded Python interpreter. The Python scripts the program uses as input obviously refer to the C-defined objects and functions. I'd now like to make some of these objects pickleable.
泡菜文档描述了如何使用__reduce__
使扩展类型可泡菜.但这是一个Python方法-如何在底层PyObject中定义它?
The pickle docs describe how extension types can be made picklable using __reduce__
. But this is a Python method - how would I define this in the underlying PyObject?
完全确定我误会了一些东西...
Fairly sure I'm mis-understanding something...
推荐答案
pickle
模块既有纯Python版本又有C变体(称为cPickle
).因此,__reduce__
方法需要可以从Python代码中调用.
The pickle
module comes in both a python-only and a C variant (called cPickle
). As such, the __reduce__
method needs to be callable from Python code.
因此,您需要在C对象中提供__reduce__
条目 PyMethodDef
struct 以及合适的实现.
Thus, you need to provide a __reduce__
entry in your C object PyMethodDef
struct with a suitable implementation.
或者,您也可以在 copy_reg
模块中注册一个酸洗功能.该模块的原始用例是更好地支持扩展模块.模块状态的源代码:
Alternatively, you can also register a pickling function with the copy_reg
module. This module's original usecase was to support extension modules better; the source code for the module states:
这仅对添加C语言中定义的扩展类型的pickle支持有用,不适用于用户定义类的实例.
This is only useful to add pickle support for extension types defined in C, not for instances of user-defined classes.
这篇关于python:腌制c对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!