I have an interface that is called by unmanaged code. It passes a BSTR type but the data is in ascii string. When it’s being written to the file I’m seeing unexpected characters. My thinking of how the data would travel Unmanaged[BSTR[ASCII]] –> Managed[String[ASCII]] –> File[Unicode[ASCII]] so the characters at the input should be the same as those at output. Is this correct? The interface function being called by the unmanaged code is below.
//C# interface called by unmanged code
public void WriteOutFile([In] [MarshalAs(UnmanagedType.BStr)] String asciiData)
{
File.WriteAllText(fileName, asciiData);
}
First, .NET strings are always unicode strings. You can get any representation of concrete string, using corresponding encoding, but all of chars in the string are unicode chars.
Second, if you are using UnmanagedType.BStr, then unmanaged code must pass BSTR and solve character encoding problems itself (ASCII is single byte, BSTR is double byte). If it is impossible, you should consider another type for marshaling, e.g. UnmanagedType.LPStr.