3

In C++ we can access members of a guid in the following way:

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

The structure of guid in C++ is:

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

Question: How to translate the third line in the C++ code (dwRand = guid.Data1 & 0x7FFFFFFF;). In other words - how to access guid members? There's no such thing in C#.

Thanks in advance!

2
  • Is this .NET C++, or standard C++? If the latter, where are you getting your GUID class from? Commented Mar 24, 2009 at 21:47
  • FYI: since some (quite old) version of Windows, GUIDs aren't composed in a simple way from the MAC, date/time and randomizer number or whatever. Try generating a few GUIDs with guidgen. Commented Mar 24, 2009 at 21:53

2 Answers 2

5

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 modify a Guid:

Guid g = GetGuidFromSomewhere(); MyGuid mg = new MyGuid(g); mg.Data1 &= 0x7FFFFFFF; g = mg.ToGuid(); 
Sign up to request clarification or add additional context in comments.

Comments

5

You can use Guid.ToByteArray to get the values as bytes, but there are no accessor methods/properties for the "grouped" bytes. You could always write them as extension methods if you're using C# 3 though.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.