P/Invoke,c#:无符号字符丢失一个字节
我正在为软件的 SDK 编写 dll 文件,并尝试调用一个函数来获取有关软件主机的信息。
函数需要的结构中有两个 unsigned char 变量(HostMachineAddress、HostProgramVersion),当我尝试从 c# 调用它时,似乎我“松动”了最后一个字节...如果我将下面的 c# 结构中的 SizeConst 更改为5 我确实得到了丢失的字节,但是它导致其他变量丢失数据。
有人可以帮我找到解决这个问题的方法吗?还尝试使用类而不是结构会导致 system.stackoverflow 错误
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C# 结构体的布局与 C++ 结构体的布局不同(HostProgramVersion 应位于最后)。
另外,对于编组为
ByValTStr
的字符串,请使用[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
。缺少最后一个字节的问题可能是编组器尝试将 null 附加到您的字符串(如以 null 结尾的字符串)。尝试使用 sbyte[]+ByValArray 而不是字符串。
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.