gpt4 book ai didi

python - 什么是 SwigPyObject 对象?

转载 作者:太空狗 更新时间:2023-10-29 18:07:32 25 4
gpt4 key购买 nike

当我尝试使用

保存自定义对象时出现错误

以 open(path + '/' + 'my_object.pickle', 'wb') 作为句柄:
pickle.dump(my_class_instance, handle, protocol=pickle.HIGHEST_PROTOCOL)

错误信息是:

TypeError: can't pickle SwigPyObject objects

我的第一个问题是:什么是 SwigPyObject 对象?,因此我可以尝试找出错误的来源。

最佳答案

什么是 SWIG?

Simplified Wrapper and Interface Generator (SWIG) 是一种开源软件工具,用于将用 C 或 C++ 编写的库与脚本语言(如 Python)连接起来。 SWIG 的一个众所周知的替代品是 Boost。 Boost Library旨在完成同样的事情。

您使用 SWIG 创建一个用 C/C++ 开发的 Python 库(用于与现有 C/C++ 库的互操作性或提高性能等)。

引用SWIG documentation :

To build Python extension modules, SWIG uses a layered approach in which parts of the extension module are defined in C and other parts are defined in Python. The C layer contains low-level wrappers whereas Python code is used to define high-level features.

This layered approach recognizes the fact that certain aspects of extension building are better accomplished in each language (instead of trying to do everything in C or C++). Furthermore, by generating code in both languages, you get a lot more flexibility since you can enhance the extension module with support code in either language.

什么是 SwigPyObject 对象?

SwigPyObject 对象在 SWIG documentation 的主题“有关 Python 类接口(interface)的更多详细信息”中进行了描述。 .

这个对象是一个实现细节。它由以下 C 结构定义:

typedef struct {
PyObject_HEAD
void *ptr;
swig_type_info *ty;
int own;
PyObject *next;
PyObject *dict;
} SwigPyObject;

SwigPyObject 对象存储 C++ 对象的实例:

When -builtin is used, the pure python layer is stripped off. Each wrapped class is turned into a new python built-in type which inherits from SwigPyObject, and SwigPyObject instances are returned directly from the wrapped methods.

pickle 文件

您的 pickle 文件中包含的数据包含一个 SwigPyObject 对象,但您的解释器不知道如何反序列化它。您需要检查您的 virtualenv 是否包含提供您的 pickle 对象的 Python/C++ 库。

关于python - 什么是 SwigPyObject 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45586522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com