如何在瓦拉中从Gee.Map中检索结构(装箱)项



我有以下示例代码。具有(Foo(类项的Map和具有(Bar(结构项的Map:

public class Maps {
Gee.Map<Foo?, int> map1 = new Gee.HashMap<Foo?, int> ();
Gee.Map<Bar?, int> map2 = new Gee.HashMap<Bar?, int> ();

public Maps () {
Foo a = new Foo ();
Foo b = new Foo ();
Foo c = new Foo ();
map1.set (a, 1);
map1.set (b, 2);
map1.set (c, 3);
stdout.printf ("Foo = %d %d %d %dn", map1.get (a), map1.get (b), map1.get (c), map1.size);
Bar e = Bar ();
Bar d = Bar ();
Bar f = Bar ();
map2.set (d, 1);
map2.set (e, 2);
map2.set (f, 3);
stdout.printf ("Bar = %d %d %d %dn", map2.get (d), map2.get (e), map2.get (f), map2.size);
}
}
public class Foo {
public string name;
public Foo () {
name = "foo";
}
}
public struct Bar {
public string name;
public Bar () {
name = "bar";
}
}
public static int main (string[] args) {
stdout.printf ("Startn");
var a = new Maps ();
stdout.printf ("Endn");
return 0;
}

输出:

Start
Foo = 1 2 3 3
Bar = 0 0 0 3
End

我做错了什么,不能从map2中检索值?

在浏览GNOME源代码后,我发现了以下解决方案(来自Geary(:

即添加自定义散列和相等函数。

Gee.Map<Bar?, int> map2 = new Gee.HashMap<Bar?, int> (bar_hash_func, bar_equal_func);
public static uint bar_hash_func (Bar? n) {
return hash_memory ((uint8 *) n, sizeof(Bar));
}
public static bool bar_equal_func (Bar? a, Bar? b) {
Bar *bia = (Bar *) a;
Bar *bib = (Bar *) b;
return (*bia) == (*bib);
}
/**
* A rotating-XOR hash that can be used to hash memory buffers of any size.
*/
public static uint hash_memory (void *ptr, size_t bytes) {
if (ptr == null || bytes == 0) {
return 0;
}
uint8 *u8 = (uint8 *) ptr;
// initialize hash to first byte value and then rotate-XOR from there
uint hash = *u8;
for (int ctr = 1; ctr < bytes; ctr++) {
hash = (hash << 4) ^ (hash >> 28) ^ (*u8++);
}
return hash;
}

最新更新