如何通过接口获取对象的地址? [英] How do I get the address of an object with an interface?

查看:57
本文介绍了如何通过接口获取对象的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与使用接口布置类?

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个字节的偏移量。那是不对的。如何从接口获取正确的地址?

So the address of Bar has an offset of 24 bytes. That can't be right. How do I get the correct address from an interface?

推荐答案

https://dlang.org/spec/abi.html#classes


将类对象投射到接口包括将接口的对应vptr的偏移量添加到对象基址的地址。将接口ptr转换回其来源的类类型涉及获取正确的偏移量以从对象中减去它。vtbl[0]处的接口条目。

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].

我不知道为什么这是必要的,但似乎可以解释不同的地址。

I don't know why this is necessary, but it seems to explain the different addresses.

这篇关于如何通过接口获取对象的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆