Search code examples
c#pinvokemarshalling

How to unmarshal a pointer to an array that should later be freed?


I want to invoke the AuditEnumerateCategories function from a C# program, for which I am declaring the external function like this:

[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool AuditEnumerateCategories(
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] out Guid[] auditCategories,
    out uint numCategories);

And then I can use it in my code as:

if (AuditEnumerateCategories(out Guid[] categories, out uint dummySize)) 
{
    ...
}

This works fine, but then I noticed the following in the docs regarding the array that is returned as the first argument:

When you have finished using this buffer, free it by calling the AuditFree function.

Is there a way of getting an IntPtr out of that categories variable that I can use to invoke the AuditFree function? Or should I declare AuditEnumerateCategories as returning an IntPtr and do the marshalling to Guid[] myself?


Solution

  • The framework won't do this automatically for you. You'll need to declare the parameter as an IntPtr and do all the marshaling manually.