uuidcreate (rpcrt4)
Last changed: -130.226.238.69

.
Summary
Create a new UUID

C# Signature:

[DllImport("rpcrt4.dll"]
static extern int UuidCreate(ref UUID id);

VB Signature:

Declare Function UuidCreate Lib "rpcrt4.dll" (ByRef id As UUID) As Integer

User-Defined Types:

[StructLayout(LayoutKind.Sequential)]
private struct UUID
{
     public ulong Data1;
     public ushort Data2;
     public ushort Data3;
     [MarshalAs(UnmanagedType.ByValTStr, SizeConst=8)]
     public string Data4;
}

private const int RPC_S_OK = 0;
private const int RPC_S_OUT_OF_MEMORY = 14;
private const int RPC_S_UUID_LOCAL_ONLY = 1824;

Alternative Managed API:

Do you know one? Please contribute it!

Notes:

None.

Tips & Tricks:

Please add some!

Sample Code:

UUID id = new UUID();
rc = UuidCreate(ref id);
if (rc != RPC_S_OK && rc != RPC_S_UUID_LOCAL_ONLY)
{
     // Handle error
}

Typically, the UUID is required as a string. Here is how:

[DllImport("rpcrt4.dll")]
private static extern int UuidToString(ref UUID uuid, ref System.IntPtr str);

[DllImport("rpcrt4.dll")]
private static extern int RpcStringFree(ref System.IntPtr str);

public static string generateUUID()
{
     int rc;

     UUID id = new UUID();
     rc = UuidCreate(ref id);
     if (rc != RPC_S_OK && rc != RPC_S_UUID_LOCAL_ONLY)
     {
     throw <cannot create UUID exception>;
     }

     System.IntPtr str = new System.IntPtr();
     rc = UuidToString(ref id, ref str);
     switch(rc)
     {
     case RPC_S_OK:
     {
         break;
     }
     case RPC_S_OUT_OF_MEMORY:
     {
         throw <out of memory excepetion>;
     }
     default:
     {
         throw <UuidToString failed exception>;
     }
     }

     string result;
     try
     {
     result = Marshal.PtrToStringAnsi(str);
     }
     catch(System.Exception ex)
     {
     throw <PtrToStringAnsi failed exception>;
     }
     if ((rc = RpcStringFree(ref str)) != RPC_S_OK)
     {
     throw <RpcStringFree failed exception>;
     }
     return result;
}

Documentation
UuidCreate @msdn on MSDN