使用 C# 将非托管结构编组为托管代码

发布于 2024-07-25 02:33:17 字数 357 浏览 2 评论 0原文

当我从外部应用程序获取字节时,我需要处理字节[]。 外部应用程序也是用 C# 完成的,它们通过 UDP 发送字节。 他们正在发送从结构转换而来的字节,如下所示:

public struct DISPATCH_MESSAGE
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public char[] federation_name; // Units: nil     Range: nil
}

因此,当我获取字节时,我需要取出其中的 char[] , 并从 char[] 中取出字符串。

我对这种非托管编码很陌生。

I need to process the bytes[] when I get from external application. The external application is also done in C# and they send the bytes thru UDP. They are sending the bytes converted from struct which is stated below :

public struct DISPATCH_MESSAGE
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public char[] federation_name; // Units: nil     Range: nil
}

So, when I get the bytes, I need to take out the char[] inside that,
and get the string out of that char[].

I am new to this kind of unmanaged coding.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心舞飞扬 2024-08-01 02:33:17

也许您应该将其声明为 ByValTStr (根据字符串的性质,它可能会有所不同):

 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
 public struct DISPATCH_MESSAGE{ 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]   
    public string federation_name; 
 }

更新: 如果它已经给出了 char[],它可能正确地进行了必要的转换(包括处理编码),所以我认为您只需要:

string str = new string(instance.federation_name);

Probably you should declare it as ByValTStr (depending on the nature of the string, it might be different):

 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
 public struct DISPATCH_MESSAGE{ 
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]   
    public string federation_name; 
 }

UPDATE: If it's already giving out a char[], it's probably doing the necessary conversion (includes handling encoding) correctly, so I think you'd just need:

string str = new string(instance.federation_name);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文