Access Guid Members in C #

In C ++, we can address directive members as follows:

GUID guid = {0};
CoCreateGuid(&guid);
dwRand = guid.Data1 & 0x7FFFFFFF;

The guid structure in C ++:

Data 1 - unsigned long
Data 2 - unsigned short
Data 3 - unsigned short
Data 4 - unsigned char

Question: how to translate the third line into C ++ ( dwRand = guid.Data1 & 0x7FFFFFFF;) code . In other words - how to get access to leading members? In C # there is no such thing.

Thanks in advance!

+3
source share
2 answers

You can create a structure:

public struct MyGuid
{
    public int Data1;
    public short Data2;
    public short Data3;
    public byte[] Data4;

    public MyGuid(Guid g)
    {
        byte[] gBytes = g.ToByteArray();
        Data1 = BitConverter.ToInt32(gBytes, 0);
        Data2 = BitConverter.ToInt16(gBytes, 4);
        Data3 = BitConverter.ToInt16(gBytes, 6);
        Data4 = new Byte[8];
        Buffer.BlockCopy(gBytes, 8, Data4, 0, 8);
    }

    public Guid ToGuid()
    {
        return new Guid(Data1, Data2, Data3, Data4);
    }
}

Now, if you want to change Guid:

Guid g = GetGuidFromSomewhere();
MyGuid mg = new MyGuid(g);
mg.Data1 &= 0x7FFFFFFF;
g = mg.ToGuid();
+4
source

You can use Guid.ToByteArrayto get the values ​​in bytes, but there are no access methods / properties for the "grouped" bytes, you can always write them as extension methods if you use C # 3.

+5
source

Source: https://habr.com/ru/post/1705289/


All Articles