views:

49

answers:

1

So I'm trying to invoke a function I have in my unmanaged C++ dll.

void foo(char* in_file, char * out_file)

In my C# application I declare the same function as

[DllImport("dll.dll")]
public static extern void foo(byte[] in_file, byte[] out_file);

The actual parameters I pass through an ASCII encoder like so

byte[] param1 = Encoding.ASCII.GetBytes(filename1);
byte[] param2 = Encoding.ASCII.GetBytes(filename2);
foo(param1, param2);

Everything works, except when the length of param1 is 0 or 36 or 72 characters (bytes). Then for some reason the DLL reports the received length of 1, 38, 73 with the 0x16 character appened on the very end.

I have wasted half a day trying to debug and understand why this is happening. Any ideas? What is the significance of multiples of 36?

Edit/Solution:

After I posted this a possible answer struck me. By appending the null character 0x0 to the end of my strings before converting them to byte arrays I have eliminated the problem. Although I'm not sure if that is by design.

+2  A: 

You've stumbled across the answer yourself - nowhere is the length passed to the function.

You need to think carefully about what functions you are running these on and whether ASCII is really what you want.

You probably really want this, with no ASCII encoding necessary and null termination explicit in the marshaled type:

[DllImport("dll.dll")]
public static extern void foo(
    [MarshalAs(LPStr)] string in_file,
    [MarshalAs(LPStr)] string out_file);

But check your foo() implementation and make sure you understand what you really expect to be passed in.

EWizard