C++/CLI Wrapper – marshalling GUIDs

GUIDs, unique identifiers which can be assigned to items in C# and C++ are another set of variables which, despite sharing many characteristics, need to be marshalled between the C# implementation and C++ implementations when using the CLI wrapper.

Marshalling GUIDs between System.Guid and GUID

GUIDs are useful variables to pass between C# and C++ when working in both languages. They are unique in both, but can be passed across and assigned in each language so they can refer to the same portion of data. This makes it easy to match data up between the two languages, particularly if working between Dictionarys (C#) and Maps (C++). The GUID will identify the data uniquely, so you can guarantee you can call the equivalent data when you cross languages.

To marshal between them, you need two new functions in your C++/CLI code. One will convert a GUID to System.Guid, and the other will convert System.Guid to GUID. The code for both is shown below.

Converting GUID to System.Guid

Guid FromGUID(GUID guid) {
    return Guid(guid.Data1, guid.Data2, guid.Data3, 
        guid.Data4[0], guid.Data4[1], 
        guid.Data4[2], guid.Data4[3], 
        guid.Data4[4], guid.Data4[5], 
        guid.Data4[6], guid.Data4[7] );
};

Converting System.Guid to GUID

GUID ToGUID(Guid guid) {
    array^ guidData = guid.ToByteArray();
    pin_ptr data = &(guidData[ 0 ]);
    return *(_GUID *)data;
};
Marshalling GUIDs between System.Guid and GUID

Marshalling GUIDs between System.Guid and GUID

Comments

  1. By Yijiang Huang

  2. By FraserG

Leave a Reply

Your email address will not be published. Required fields are marked *