views:

679

answers:

5

I've got a C# program that needs to pass a char buffer to an unmanaged function. I've found two ways that seem to work reliably, but I'm not sure which I should choose.

Here's the unmanaged function's signature.

extern "C" __declspec(dllexport) int getNextResponse(char *buffer);

The first option is to define the buffer as a StringBuilder, as follows.

//at class level...
[DllImport("mydll.dll")]
static extern int getNextResponse(StringBuilder buffer);

//in main method body...
StringBuilder sb = new StringBuilder(" ", 65536);
int rc = getNextResponse(sb);

This is simple, and it works, and I think I basically understand why it works because the StringBuilder has a buffer behind the scenes, so (I assume) the interop layer is just marshalling the StringBuilder to a char *.

The other option is using unsafe code.

//at class level...
[DllImport("mydll.dll")]
static extern int getNextResponse(byte* buffer);

//separate method...
private static unsafe int runGetNextResponse(byte[] buffer)
{
    fixed (byte* p = buffer)
    {
        int rc = getNextResponse(p);
        return rc;
    }            
}

//in main method body...
byte[] b = new byte[65536];
int rc = runGetNextResponse(b);

The second approach is more code, but it's also more explicit about what's going on.

Are these two approaches doing basically the same thing? Is there any reason to choose one over the other?

+2  A: 

While I can't weigh in definitively, I can share my own experiences. I have used the StringBuilder method exclusively and have had no problems with it. I like the simpler code of it and the avoidance of unsafe.

Richard Morgan
+6  A: 

I'd strongly prefer using the StringBuilder version.

There's not going to be a huge difference between the two, and using unsafe code is not nearly as clean.

In my opinion, since there is a way to solve the problem using a core library class, using unsafe code without a clear (and needed) benefit is a premature optimization.

chills42
What happens if the Garbage Collector reallocate the StringBuilder passed without a fixed statement during the getNextResponse execution?Every pointer parameter used in imported functions shall be fixed? Or am I missing seomthing?
Luca
+2  A: 

While using a StringBuilder is preferred there's one caveat. Imagine for example that in your getNextResponse method you store the pointer to some static variable and use it in another method:

char* globalPointer;

int getNextResponse(char *buffer) {
    globalPointer = buffer;
    return 0;
}

void someOtherMethod() {
    printf("%s\n", globalPointer);
}

Now let's look at the managed side:

var sb = new StringBuilder();
sb.Append("Hello World");
int result = getNextResponse(sb);
Console.WriteLine(result);
someOtherMethod(); // kaboom: The GC could have already destroyed the string builder.

The unsafe method guarantees you that the memory location won't be moved around:

byte[] buffer = Encoding.UTF8.GetBytes("Hello World");
fixed (byte* p = buffer)
{
    int result = getNextResponse(p);
    Console.WriteLine(result);
    someOtherMethod(); // works fine as the buffer address is pinned down in memory
}

In this case the unsafe version will work better.

Darin Dimitrov
A: 

It depends on what the data in the buffer actually is. If it is character data use the StringBuilder approach. If it is binary data use a byte array instead, but don't use the unsafe method. While the exaggerated fear of 'unsafe' that is getting common is a little silly and there is no reason not to use it when warranted, in this case it is unnecessary. Use:

//at class level...
[DllImport("mydll.dll")]
static extern int getNextResponse([In, Out] byte[] buffer);

//in main method body...
byte[] buffer = new byte[65536];
int rc = getNextResponse(buffer);
Stephen Martin
+1  A: 

It depends on the cost of marshalling. If you do a lot of marshalling or the data being marshalled is large, you may want to reuse the buffer instead of creating/destroying the buffer every time.

Sheng Jiang 蒋晟