我在 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
:
[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 );
关于c# - 将 ASCII 字符数组转换为 UNICODE 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28234173/