【问题标题】:convert ASCII character array to UNICODE string将 ASCII 字符数组转换为 UNICODE 字符串
【发布时间】:2015-03-29 19:51:30
【问题描述】:

我在 c# 中调用一个 c dll 函数,它返回一个 64 位 ASCII 字符数组,因为 c# 使用 UNICODE 如何将 ASCII 字符数组转换为 UNICODE 字符串?

我之前通过将字符串放在结构中来做到这一点,因为该函数将结构作为其参数之一,如下所示:

      public struct example
      {
        public uint ID;  
        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 64)]
        public string serialNumber;  
      }                  

这次我不能使用结构,因为这个新函数将 serialNumber 作为其参数之一。我已经将serialNumber声明为字符串,然后调用导入的c函数时程序崩溃,我估计是这个数据冲突导致的?

抱歉,如果这个问题有点令人困惑,我会尽力解释我的问题,我们将不胜感激。

【问题讨论】:

  • 添加System.Runtime.InteropServices.CharSet.Ansi
  • 抛出一个错误,说 Ansi 确实存在于 System.Runtime.InteropServices.CharSet 类型中。抱歉,我是编程新手
  • 我应该在开头添加吗?

标签: c# c user-interface unicode ascii


【解决方案1】:

你需要像这样使用System.Runtime.InteropServices.CharSet.Ansi:

[StructLayout( LayoutKind.Sequential, CharSet = CharSet.Ansi )]
public struct example
{
    public uint ID;  
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 64)]
    public string serialNumber;  
}

您还可以将您的字符串声明为字节数组并稍后使用:

myString = System.Text.Encoding.ASCII.GetString( byteArray );

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 2010-12-09
    • 2011-09-19
    • 1970-01-01
    • 2018-11-19
    • 2018-11-18
    相关资源
    最近更新 更多