This is because List has not yet been allocated.
You will need to initialize all the fields.
Another problem that I see is the following:
IntPtr uList = Marshal.AllocHGlobal(Marshal.SizeOf(userList)); ... result = GetUsers(out uList);
Are you sure that out should not be ref ? Otherwise, it makes no sense (not sure if ref is correct either).
Update. Once again looking at your code, you should do this (and avoid memory leaks, causing your attention).
IntPtr uList; var result = GetUsers(out uList); var userlist = (USER_LIST) Marshal.PtrToStructure(ulist, typeof(USER_LIST)); Marshal.FreeHGlobal(ulist);
Refresh again:
Your p / invoke signature is most likely incorrect or you misinterpret it.
I can probably guess something like:
int GetUsers(USER_LIST* ulist);
And this is what you have - it is not the same thing.
If so, the decision is easy.
Change USER_LIST to a class (but keep a consistent layout) and use
// pinvoke sig int GetUsers(USER_LIST ulist); var ulist = new USER_LIST(); // initialize fields var r = GetUsers(ulist);
- or -
Name it ref .
// pinvoke sig int GetUsers(ref USER_LIST ulist); var ulist = new USER_LIST(); // initialize fields var r = GetUsers(ref ulist);
This way, you donβt have to bother with the manual sorter, and I donβt see the possibility of a memory leak.
Final update:
Given the signature you sent, it looks like this: GetUsers returns a pointer to the USER_LIST list with the return value, which is the counter. Good memory leak there.
In any case, I would probably experiment with an unsafe approach here and just go through the result and make sure everything is freed. (I still think you should shoot the author).