Re: [Vala] Unions in Vala



Thanks for your reply,

2012/7/19 sejerpz tin it <sejerpz tin it>

pointers are missing too.

That isn't true see:

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


I missed them the first time. Good to know they're available.

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;

}
}


This actually works efficiently. I worked out a solution involving a class
and pointers:

    public class Reg
    {
        private uint16 _hl;
        private uint8 *_h;
        private uint8 *_l;

        public uint16 Value
        {
            get { return _hl; }
            set { _hl = value; }
        }

        public uint8 High
        {
            get { return *_h; }
            set { *_h = value; }
        }

        public uint8 Low
        {
            get { return *_l; }
            set { *_l = value; }
        }

        public Reg()
        {
            uint16 *_tmp16 = &_hl;

            _h = (uint8 *)(((ulong)(_tmp16)) + 1);
            _l = (uint8 *)((ulong)(_tmp16));
        }
    }

My solution is far slower (declaring my class is at least one of magnitude
slower than declaring your struct; manipulation is between 1.5 and 2 times
slower), but I find it nicer because I can do things like:
     reg.Low += 1;
instead of:
    word.set_lo (word.get_lo () + 1);

Once said that, though, I think I'll go with your solution as I'm seeing
that my class's low performance becomes an issue.

Thanks again

--
nadir


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