如何从C#中获取UTF-8中的字符串到C DLL

How can I get and send string in UTF-8 from c# to c++ dll

本文关键字:字符串 DLL 获取 UTF-8      更新时间:2023-10-16

我对此有问题:

FileStream stream = new FileStream("Configuration.xml", FileMode.Open);
Encoding u8 = new UTF8Encoding(true, true);
StreamReader reader = new StreamReader(stream, u8);
string str = reader.ReadToEnd();

configuration.xml在UTF-8中,但是str不在,然后我应该将此str发送到我的dll,dll函数不适用于noutf-8

如果您确实需要从C#字符串开始,则必须将该字符串转换为UTF-8,存储在字节数组中:

byte[] utf8 = Encoding.UTF8.GetBytes(str);

然后将该字节数组传递到DLL。请注意,字节数组不会被终止终止,因此,如果DLL需要空末端,则需要明确添加它。

在另一方面,避免从UTF-8到UTF-16然后再次回到UTF-8的行程可能会容易得多。因此,不要使用StreamReader在字符串中读取。将文件的内容直接读取到字节数组中。

byte[] utf8 = File.ReadAllBytes("Configuration.xml");

再次,这将没有零端,因此,如果需要,则必须添加它。

如果您确实需要一个null末端,则FileStream可能会更容易:

  1. 在读取模式下创建FileStream
  2. 通过阅读Length属性来查找文件的大小。
  3. 分配长度Stream.Length+1字节的字节阵列。新的内存将被零定位化,因此最终的字节已经具有您的null末端。
  4. 在文件流上调用Read,以将Stream.Length字节读取到字节数组中。

类似的东西:

byte[] ReadAsNullTerminatedByteArray(string filename)
{
    using (FileStream fs = File.OpenRead(filename))
    {
        byte[] bytes = new byte[fs.Length+1];
        fs.Read(bytes, 0, fs.Length);
        return bytes;
    }
}