简体   繁体   中英

convert ASCII character array to UNICODE string

I am calling ac dll function in c# which returns a 64 bit ASCII character array, since c# uses UNICODE how do I convert the ASCII character array to a UNICODE string?

I have done this before by having the string in a struct because the function had a struct as one of its arguments as follows:

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

I cannot use a structure this time as this new function has serialNumber as one of its arguments. I have declared the serialNumber as a string, then when the imported c function is called the program crashes, I reckon This data conflict is the cause of that?

Sorry if this question is a bit confusing trying my best to explain my problem, any help would be appreciated.

You need to use System.Runtime.InteropServices.CharSet.Ansi like this :

[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;  
}

You can also declare your string as a byte array and convert later using :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM