<StructLayout(LayoutKind.Sequential, Pack:=1)> Public Structure error_last_msg <MarshalAs(UnmanagedType.ByValArray, SizeConst:=512)> Public data() As Byte End Structure si = Marshal.SizeOf(error_last_msg1) Dim error_last_msg1_ptr As IntPtr = Marshal.AllocCoTaskMem(si) i = PassThruGetLastError(error_last_msg1_ptr) Dim s As String = Marshal.PtrToStringAuto(error_last_msg1_ptr, 512) 

Why crash on reading from memory?

System.AccessViolationException: Attempting to read or write to protected memory. This often indicates that the other memory is damaged. System.Runtime.InteropServices.Marshal.PtrToStringUni (IntPtr ptr, Int32 len) in System.Runtime.InteropServices.Marshal.PtrToStringAuto (IntPtr ptr, Int32 len)

  • Here in the last line 512 is "number of characters to copy", and characters are treated as Unicode judging by the stack => you are trying to read 512 characters = 1024 bytes instead of 512 bytes. - nzeemin
  • I tried instead of auto put ancy the same result - Dow Jhob

0