Skip to main content
 首页 » 编程设计

python之在 Python 中使 SWIG 包装内置类 "hashable"

2025年05月04日10mengfanrong

我使用 SWIG将我们的 C++ 库暴露给 Python。出于性能原因,我有兴趣将一些包装切换为使用 SWIG 的 -builtin选项,它删除了 Python 代理对象的层。

但是,包装类不能再用于 Python 集中或作为 Python 字典中的键。它是不可散列的!

>>> wrapped_object = WrappedObject() 
>>> hash(wrapped_object) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: unhashable type: 'structure.WrappedObject' 

我已经为我的类定义了 __hash__()、__eq__() 和 __ne__() 方法。

>>> wrapped_object.__hash__ 
<built-in method __hash__ of structure.WrappedObject object at 0x7fa9e0e4c378> 
>>> wrapped_object.__eq__ 
<method-wrapper '__eq__' of structure.WrappedObject object at 0x7fa9e0e4c378> 

我需要做什么才能使此类可哈希?

请您参考如下方法:

对于内置对象,Python 使用散列 slot ( Python docs link ) 而不是 __hash__() 方法。因此,新的内置对象需要填充哈希槽。这需要一个特定的方法原型(prototype)。

在 WrappedObject C++ 文件中:

long WrappedObject::getHash(); 

并且在 SWIG 包装器定义文件中:

%rename(__hash__) WrappedObject::getHash; 
%feature("python:slot", "tp_hash", functype="hashfunc") WrappedObject::getHash; 

这对我有用!