Structural Marshal in C #

I have the following structure in C #

unsafe public struct control { public int bSetComPort; public int iComPortIndex; public int iBaudRate; public int iManufactoryID; public byte btAddressOfCamera; public int iCameraParam; public byte PresetNum; public byte PresetWaitTime; public byte Group; public byte AutoCruiseStatus; public byte Channel; public fixed byte Data[64]; } 

And the function that I use to convert to a byte array [] is

  static byte[] structtobyte(object obj) { int len = Marshal.SizeOf(obj); byte[] arr = new byte[len]; IntPtr ptr = Marshal.AllocHGlobal(len); Marshal.StructureToPtr(obj, ptr, true); Marshal.Copy(ptr, arr, 0, len); Marshal.FreeHGlobal(ptr); return arr; } 

When I compile it, it gives

 Type 'System.Byte[]' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed. 

What could be the problem? Thanks in advance!

+6
source share
2 answers

SizeOf does not work with arrays. Use array.Length * Marshal.SizeOf(elementType) .

+3
source

The error you report as a compilation error is actually a runtime error ( ArgumentException ). If you want to use structtobyte to convert control to byte[] , you must pass the control reference to the method, not the byte array ( byte[] ).

 control ctrl = new control(); byte[] bytes = structtobyte(ctrl); 
-1
source

Source: https://habr.com/ru/post/890830/


All Articles