Marshal struct with array member in C# -


I am using C / with P / I to invite to access a DLL method. The definition of the method is as follows:

  [DllImport ("userManager.dll")] static extern int GetUsers (IntPtr userList outside);  

Basic Structures:

  Type-tof format user_list {unsigned short numbers; USER_LIST_ITEM list [VARLEN]; } USER_LIST typedef struct user_list_item {Name Name [260]; Unsigned four addresses [256]; } USER_LIST_ITEM  

And the straight line I have taken is the following:

  [Layout layout (LayoutCind.Secure)] Public class USER_LIST {public UITMUUsers; [Marshall AS (unmanaged type. BevalArere)] Public USER_LIST_ITEM [] list; } [Layout Layout (LayoutCind.Security)] Public Class USER_LIST_ITEM {[Marshall AS (UnmanagedType.ByValTStr, SizeConst = 260)] Public String Name; [Marshall AS (UnmanagedType.ByValTStr, SizeConst = 256)] Public String Address; };  

But when I try to open it, I get an error:

  USER_LIST userList = new USER_LIST (); // Indicator indicator IntPtr uList = Marshall AllocHGlobal (Marshal.SizeOf (userList)); Martial StructureOutPrint (UserList, ULast, False); Results = Getuures (Exiting); Martial.tterstrokes (ULIIT, USEUV); & Lt; - Runtime has encountered a serious error. The error address was at 0x79f82af6, thread 0x464 at. Error code is 0xc0000005 This error can be a bug in CLR or a bug in the unsafe or non-verified parts of the user code. Common sources of this bug include user martial errors for CAM Interop or Pinevoc, which can corrupt the stack.   

I get the NumUsers property correct, but it seems that the error occurs when the array. Any ideas?

If you specify an array in a structure then as Parameter, you need Marshar to tell which length is the array. With your code, Marshaller is probably allocating a zero-length array or just using null , which produces a crash. Unfortunately there is no way to specify a variable-length outside as a member of a structure, because Marshall AS The SIPA Param Index works for methods only . You can participate with specifying a large, stable-size array using MarshalAs.SizeConst , but generally you have to parse (potentially allocated) return buffers like this :

var count = Marshal.ReadInt32 (uList); Var user = new list & lt; USER_LIST_ITEM & gt; (); Var ptr = (long) uList + 4; (Int i = 0; I & lt; counts; ++ i) {users.Add (martial.pritistcture (typef (USER_LIST_ITEM), new INTERPTR (PTR)); Ptr + = Marshal.SizeOf (typeof (USER_LIST_ITEM)); }

You have to pay extra attention to alignment and padding and 32/64 bit issues.


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -