Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

P/Invoke a Function Passed a StringBuilder

in a C# file i have a

class Archiver {
    [DllImport("Archiver.dll")]
    public static extern void archive(string data, StringBuilder response);
}

string data is an input, and StringBuilder response is where the function writes something

the archive function prototype (written in C) looks like this:

void archive(char * dataChr, char * outChr);

and it receives a string in dataChr, and then does a

strcpy(outChr,"some big text");

from C# i call it something like this:

string message = "some text here";
StringBuilder response = new StringBuilder(10000);
Archiver.archive(message,response);

this works, but the problem, as you might see is that i give a value to the StringBuilder size, but the archive function might give back a (way) larger text than the size i've given to my StringBuilder. any way to fix this?

like image 525
Andrei S Avatar asked Dec 13 '25 07:12

Andrei S


2 Answers

You need to write a function that tells you how big the StringBuilder needs to be, then call that function to initialize the StringBuilder.

like image 121
SLaks Avatar answered Dec 14 '25 19:12

SLaks


Do you control the implementation of the archive function? If you do then you have a few options.

1- Have the archive function allocate the buffer and return it to the caller. The down side is that the caller wil need to use the right function to free the buffer otherwise risk either memory leak and even corrupting the heap.

2- Pass the size of the buffer you have to the archive function so that it will not exceed the buffer length when filling the buffer.

3- If you can have a function that can return the required buffer size then you can use that. This is a common approach in the windows API, passing null as the buffer and a pointer to a DWORD which receives the required buffer size, which you can then allocate and make a second call passing the allocated buffer.

like image 39
Chris Taylor Avatar answered Dec 14 '25 20:12

Chris Taylor