gpt4 book ai didi

C# ushort[] 到字符串的转换;这可能吗?

转载 作者:行者123 更新时间:2023-11-30 19:52:13 26 4
gpt4 key购买 nike

我有一个非常痛苦的库,目前它正在接受 C# 字符串作为获取数据数组的方式;显然,这使得 pinvoke 的编码更容易。

那么如何把ushort数组按字节转成字符串呢?我试过:

int i;
String theOutData = "";
ushort[] theImageData = inImageData.DataArray;
//this is as slow like molasses in January
for (i = 0; i < theImageData.Length; i++) {
byte[] theBytes = System.BitConverter.GetBytes(theImageData[i]);
theOutData += String.Format("{0:d}{1:d}", theBytes[0], theBytes[1]);
}

我可以这样做,但它并没有在任何接近合理时间的地方完成。

我应该在这里做什么?去不安全?通过某种 IntPtr 中间体?

如果它是 C++ 中的 char*,这会容易得多...

编辑:函数调用是

DataElement.SetByteValue(string inArray, VL Length);

其中 VL 是“值长度”,一种 DICOM 类型,函数本身由 SWIG 生成为 C++ 库的包装器。似乎选择的表示形式是字符串,因为它可以相对容易地跨越托管/非托管边界,但是在项目中的整个 C++ 代码(这是 GDCM)中,char* 只是用作字节缓冲区。因此,当您想设置图像缓冲区指针时,在 C++ 中它相当简单,但在 C# 中,我遇到了这个奇怪的问题。

这是黑客攻击,我知道最好的办法可能是让 SWIG 库正常工作。我真的不知道该怎么做,宁愿在 C# 端有一个快速的解决方法,如果存在的话。

最佳答案

P/Invoke 实际上可以处理您在大多数情况下使用 StringBuilder 创建可写缓冲区之后的操作,例如参见 pinvoke.net on GetWindowText and related functions .

但是,除此之外,数据作为 ushort,我假设它是用 UTF-16LE 编码的。如果是这种情况,您可以使用 Encoding.Unicode.GetString(),但这将执行字节数组而不是 ushort 数组。要将 ushorts 转换为字节,您可以分配一个单独的字节数组并使用 Buffer.BlockCopy,如下所示:

ushort[] data = new ushort[10];
for (int i = 0; i < data.Length; ++i)
data[i] = (char) ('A' + i);

string asString;
byte[] asBytes = new byte[data.Length * sizeof(ushort)];
Buffer.BlockCopy(data, 0, asBytes, 0, asBytes.Length);
asString = Encoding.Unicode.GetString(asBytes);

但是,如果不安全代码没问题,您还有另一种选择。以 ushort* 形式获取数组的开头,并将其硬转换为 char*,然后将其传递给字符串构造函数,如下所示:

string asString;
unsafe
{
fixed (ushort *dataPtr = &data[0])
asString = new string((char *) dataPtr, 0, data.Length);
}

关于C# ushort[] 到字符串的转换;这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/274158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com