将字符串和字节数组连接到非托管内存

时间:2010-04-07 16:55:13

标签: c# memory unmanaged concatenation

这是我last question的后续内容。

我的位图图像现在有byte[]个值。最后,我将一个字符串传递给格式为String.Format("GW{0},{1},{2},{3},", X, Y, stride, _Bitmap.Height) + my binary data;的打印后台处理程序。我正在使用here中的SendBytesToPrinter命令。

到目前为止,我的代码是将其发送到打印机

public static bool SendStringPlusByteBlockToPrinter(string szPrinterName, string szString, byte[] bytes)
{
    IntPtr pBytes;
    Int32 dwCount;
    // How many characters are in the string?
    dwCount = szString.Length;
    // Assume that the printer is expecting ANSI text, and then convert
    // the string to ANSI text.
    pBytes = Marshal.StringToCoTaskMemAnsi(szString);
    pBytes = Marshal.ReAllocCoTaskMem(pBytes, szString.Length + bytes.Length);
    Marshal.Copy(bytes,0, SOMTHING GOES HERE,bytes.Length); // this is the problem line
    // Send the converted ANSI string + the concatenated bytes to the printer.
    SendBytesToPrinter(szPrinterName, pBytes, dwCount);
    Marshal.FreeCoTaskMem(pBytes);
    return true;
}

我的问题是我不知道如何将我的数据附加到字符串的末尾。任何帮助将不胜感激,如果我这样做完全错误,我可以采用完全不同的方式(例如,在移动到非托管空间之前,以某种方式将二进制数据连接到字符串。

P.S。 作为第二个问题,ReAllocCoTaskMem会在调用新位置之前移动其中的数据吗?

1 个答案:

答案 0 :(得分:2)

我建议您尽可能多地留在托管空间。使用Encoding.ASCII将字符串转换为字节数组,连接两个字节数组,然后使用结果调用本机方法。

byte[] ascii = Encoding.ASCII.GetBytes(szString);

byte[] buffer = new buffer[ascii.Length + bytes.Length];
Buffer.BlockCopy(ascii, 0, buffer, 0, ascii.Length);
Buffer.BlockCopy(bytes, 0, buffer, ascii.Length; bytes.Length);

...
bool success = WritePrinter(printer, buffer, buffer.Length, out written);
...

[DllImport("winspool.drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, byte[] pBytes, int dwCount, out int dwWritten);
相关问题