views:

201

answers:

1

This is a followup to my last question.

I now have a byte[] of values for my bitmap image. Eventually I will be passing a string to the print spooler of the format String.Format("GW{0},{1},{2},{3},", X, Y, stride, _Bitmap.Height) + my binary data; I am using the SendBytesToPrinter command from here.

Here is my code so far to send it to the printer

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;
}

My issue is I do not know how to make my data appended on to the end of the string. Any help would be greatly appreciated, and if I am doing this totally wrong I am fine in going a entirely different way (for example somehow getting the binary data concatenated on to the string before the move to unmanaged space.

P.S. As a second question, will ReAllocCoTaskMem move the data that is sitting in it before the call to the new location?

+2  A: 

I recommend you try to stay in managed space as much as possible. Convert the string to a byte array using Encoding.ASCII, concatenate the two byte arrays and then invoke the native method with the result.

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);
...

with

[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);
dtb
Do I not need to move the buffer out of managed code for the call. the example microsoft gives for the kb uses `public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);`
Scott Chamberlain
There are many ways to marshal a byte array. I didn't test it, but replacing `IntPtr` with `byte[]` in the method signature should work.
dtb
I used your method but there is a follow up question with a problem I encountered. http://stackoverflow.com/questions/2595393/
Scott Chamberlain