Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling unmanaged function from C#: should I pass StringBuilder or use unsafe code?

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?

like image 962
John M Gant Avatar asked Nov 06 '09 13:11

John M Gant


4 Answers

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.

like image 156
chills42 Avatar answered Nov 15 '22 02:11

chills42


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.

like image 31
Darin Dimitrov Avatar answered Nov 15 '22 03:11

Darin Dimitrov


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.

like image 36
Richard Morgan Avatar answered Nov 15 '22 02:11

Richard Morgan


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 string builder buffer every time.

like image 22
Sheng Jiang 蒋晟 Avatar answered Nov 15 '22 02:11

Sheng Jiang 蒋晟