P/Invoke, c#: unsigned char losing a byte
Im working towards a dll file for a software's SDK and i'm trying to call a function to get information about the host of the software.
there are two unsigned char variables(HostMachineAddress, HostProgramVersion) in the开发者_运维百科 struct the function wants and it seems like i "loose" the last byte when i try to call it from c#... if I change the SizeConst in the c# struct below to 5 i do get the missing byte, however it causes the other variable looses data.
Could someone help me find a way to solve this issue? also trying to use a class instead of struct causes system.stackoverflow error
C# Struct
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct sHostInfo
{
public int bFoundHost;
public int LatestConfirmationTime;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szHostMachineName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
public string HostMachineAddress;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szHostProgramName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
public string HostProgramVersion;
}
C#
[DllImport("Cortex_SDK.dll")]
public static extern int GetHostInfo(out sHostInfo pHostInfo);
Your C# struct's layout is different from the C++ one (HostProgramVersion should be last).
Also for strings marshalled as ByValTStr
use [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
.
The problem with the missing last byte may be that the marshaller tries to append null to your string (as in null-terminated string). Try to use sbyte[]
+ByValArray
instead of a string.
精彩评论