Return int reference in vala

时间:2015-06-25 18:31:30

标签: vala

I have a class that has fields and I want call a method of this class and get the reference to one of the fields (not the value!!). Something like this:

class Test : Object{
    uint8 x;
    uint8 y;
    uint8 z;

    uint8 method(){
        if (x == 1){
            return y;
        }else if (x == 2){
            return z;
        }
    }

    public static void main(string[] args){
        uint8 i = method(); // get reference to y or z
        i++;  //this must update y or z
    }
}

In C would be:

int& method()
{
    if (x == 1){
        return y;
    }else if (x == 2){
        return z;
    }
}

How can I achieve this in vala?

Edit: I'm trying use pointers, I have the following

public class Test : Object {

    private Struct1 stru;

    struct Struct1{
        uint8 _a;


        public uint8 a{
            get{ return _a; }
            set{ _a = value; }
        }


        public Struct1(Struct1? copy = null){
            if (copy != null){
                this._a = copy.a;
            }else{
                this._a = 0;
            }
        }

        public uint8* get_aa(){
            return (uint8*)a;

        }
    }

    public void get_pointer(){
        uint8* dst = stru.get_aa();
    }

    public static int main (string[] args){


        Test t = new Test();

        return 0;
    }

}

but when I compile I get

/home/angelluis/Documentos/vala/test.vala.c: In function ‘test_struct1_get_aa’:
/home/angelluis/Documentos/vala/test.vala.c:130:11: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
  result = (guint8*) _tmp1_;
           ^
Compilation succeeded - 2 warning(s)

Why? I am returning an uint8* type and I attempt to store it in an uint8* pointer.

1 个答案:

答案 0 :(得分:3)

C没有引用(C ++没有)。请记住,Vala将C编译为中间语言。

我认为在Vala中只有两种方法可以做到这一点:

  1. 使用框类型封装uint8值并返回对该框类型的引用。

  2. 使用指针。 (这会打开显而易见的蠕虫指针

  3. 编辑:回答您更新的示例代码问题:

    您必须非常小心,并将某些内容转换为指针类型。在这种情况下,C编译器捕获了您的虚假演员并发出警告。

    uint8 _a;
    
    // This property will get and set the *value* of _a
    public uint8 a{
        get{ return _a; }
        set{ _a = value; }
    }
    
    public uint8* get_aa(){
        // Here you are casting a *value* of type uint8 to a pointer
        // Which doesn't make any sense, hence the compiler warning
        return (uint8*)a;
    }
    

    请注意,您无法获取指针或对属性的引用,因为属性本​​身没有内存位置。

    但是,在这种情况下,您可以获得指向字段_a的指针:

    public uint8* get_aa(){
        return &_a;
    }
    

    如果您坚持要通过该物业,您必须让您的物业对指针进行操作:

        uint8 _a;
    
        public uint8* a{
            get{ return &_a; }
        }
    

    请注意,在此版本中,我删除了get_aa ()方法,该方法现在等同于a的getter。

    此外,在此代码中,属性返回一个指针,不需要setter,你只需取消引用指针即可设置值。