As you wrote it, char* buffers are allocated on the managed side. But this is the wrong place. Distribution occurs on the unmanaged side. Declare a structure in C # as follows:
[StructLayout(LayoutKind.Sequential)] public struct UserProfileData { int userProfileRevision; public IntPtr firstName; public IntPtr lastName; public IntPtr memberids; public IntPtr emailAddress; }
Then call getUserProfileData , passing struct as the output parameter. Or perhaps the ref parameter. I canβt say from here what it should be.
Your DllImport will look like this (with the correct call):
[DllImport(@"mydll.dll", CallingConvention=CallingConvention.???)] private static extern int getUserProfileData(out UserProfileData userProfile);
Then convert the returned pointers to strings as follows:
string firstName = Marshal.PtrToStringAnsi(userProfile.firstName);
etc. for other fields.
Presumably, unmanaged code also provides a function that frees the memory returned in the structure. Call it as soon as you are done with the structure.
source share