如何获取具有接口的对象的地址?
How do I get the address of an object with an interface?
这与
有关
interface Bar{
}
class Foo: Bar{
int i;
this(int _i){
i = _i;
}
}
void main(){
import std.experimental.allocator.mallocator;
import std.experimental.allocator;
auto f = Mallocator.instance.make!Foo(42);
Bar b = f;
void* p = (cast(void*)b);
void* p1 = (cast(void*)f);
writeln(p);
writeln(p1);
Mallocator.instance.dispose(b);// Bad
}
打印:
1EBE438
1EBE420
所以Bar
的地址偏移了24字节。那是不对的。如何从接口获取正确的地址?
来自https://dlang.org/spec/abi.html#classes:
Casting a class object to an interface consists of adding the offset of the interface's corresponding vptr to the address of the base of the object. Casting an interface ptr back to the class type it came from involves getting the correct offset to subtract from it from the object.Interface entry at vtbl[0].
我不知道为什么这是必要的,但它似乎解释了不同的地址。
这与
interface Bar{
}
class Foo: Bar{
int i;
this(int _i){
i = _i;
}
}
void main(){
import std.experimental.allocator.mallocator;
import std.experimental.allocator;
auto f = Mallocator.instance.make!Foo(42);
Bar b = f;
void* p = (cast(void*)b);
void* p1 = (cast(void*)f);
writeln(p);
writeln(p1);
Mallocator.instance.dispose(b);// Bad
}
打印:
1EBE438
1EBE420
所以Bar
的地址偏移了24字节。那是不对的。如何从接口获取正确的地址?
来自https://dlang.org/spec/abi.html#classes:
Casting a class object to an interface consists of adding the offset of the interface's corresponding vptr to the address of the base of the object. Casting an interface ptr back to the class type it came from involves getting the correct offset to subtract from it from the object.Interface entry at vtbl[0].
我不知道为什么这是必要的,但它似乎解释了不同的地址。