[Vala] R: Unions in Vala



Hi,

----Messaggio originale----
Da: nadirsampaoli gmail com

Data: 18-lug-2012 20.19
A: <vala-list gnome org>
Ogg: [Vala] Unions 
in Vala

I'm porting some code I wrote from procedural C to objective 
Vala and I'm
looking for the Vala-way to implement a union. I'm using 
a union in C
because I need a structure where one uin16_t and two 
uint8_t are aligned:

typedef struct {
    uint8_t lo;
    
uint8_t hi;
} WORD;

typedef union {
    uint16_t reg16;
    
WORD reg8;
} REG;

This way if I change reg8.hi's (or .lo's, for 
what matters) value,
reg16changes automatically.Now, in Vala, as far 
as I have been able to
find in
the documentation (I just started 
studying Vala, coming from a C#
background) there's no union 
keyword, 

In Vala there's no way that I know, to emulate the union 
keyword without 
resorting to polymorphic classes or mixins.

and 
pointers are missing too.

That isn't true see:

https://live.gnome.org/Vala/Tutorial#Pointers

If there's no union-
like thing in Vala, is there at least some way to make
a built-in 
type referenceable (something like .NET's Int vs int)?

I didn't 
understand this fully, but you can use  the & (address of) operator or 
define your
structure as compact classes.

I have a last resort 
solution, but it's rather inefficient, so I'd like to
know if I can 
reproduce the original C code behaviour.

Something along this code 
should also works (it's not required to derive from Reg16, anyway):


using GLib;

namespace NoUnion {
        public struct Reg16 {
                public uint16 
reg16;
        }
        
        public struct Word : Reg16 {
                public uint8 get_lo () { 
return (uint8) (reg16 & 0xFF); }
                public void set_lo (uint8 value) { 
reg16 = (reg16 & 0xFF00) | value; }
                
                public uint8 get_hi () { 
return (uint8) (reg16 >> 8); }
                public void set_hi (uint8 value) { 
reg16 = (reg16 & 0xFF) | (value << 8); }
        }
        
        public static int main
(string[] args) {
                Word word = Word();
                
                word.reg16 = 2;
                
                word.
set_lo (word.get_lo () + 1);
                word.set_hi (1);
                
                stdout.printf
("word.lo = %d | word.hi = %d | word.reg16 = %d | sizeof(Word) = %lu", 
word.get_lo (), word.get_hi (), word.reg16, sizeof(Word));
                return 0;
        
}
}


Ciao,
Andrea
_______________________________________________
vala-
list mailing list
vala-list gnome org
https://mail.gnome.org/mailman/listinfo/vala-list

 



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]