I have an unmanaged DLL that gets called from .NET with pre-allocated buffers to get filled within the unmanaged DLL (according to Pass C# string to C++ and pass C++ result (string, char*.. whatever) to C#).
My unmanaged function has the following prototype:
myFunc(char* a_inBuf, int a_InLen,
char* a_outBuf, int* a_pOutLen,
char* a_errBuf, int* a_pErrLen);
So, I declare the method in the managed code like this:
public static extern int myFunc(
[In, MarshalAs(UnmanagedType.LPStr)] string inputXml, int inputLen,
[MarshalAs(UnmanagedType.LPStr)] StringBuilder outputXml, ref int outputLen,
[MarshalAs(UnmanagedType.LPStr)] StringBuilder errorXml, ref int errorLen);
Before calling myFunc
, I create the two StringBuilders:
StringBuilder outputXml = new StringBuilder(100);
StringBuilder errorXml = new StringBuilder(100);
After calling myFunc
, I take the two StringBuilders and write them into an XML file (one for each StringBuilder) using
using (StreamWriter writer = new StreamWriter("OutputXmlFile.xml", false, Encoding.UTF8))
{
writer.Write(outputXml.ToString());
writer.Close();
}
The output shall be written in UTF8 since the Input is also UTF8. But unfortunately, the StringBuilder uses UTF16 encoding. The content of outputXml
and errorXml
gets filled in the unmanaged DLL also in UTF8 encoding. This behaviour should not be changed. When writing the files, special chars contained in the StringBuilders aren't written correctly.
How do I tell the StringBuilder that the content is actually NOT UTF16 but UTF8?
Edit: the answer provided by Polynomial indicates to use xmlWriter to write the file. But actually, the writing is just used for debugging output. In normal application run, the content of outputXml
and errorXml
is directly used within the program. Therefore, any hints regarding the use of special XML handling classes is not useful.
The actual issue is to get the correct strings out of the StringBuilder (or convert them to be correct).