apocalypse
apocalypse

Reputation: 5884

Marshaling, StringBuilder, and char pointer in DllImport

I was looking at SoundTouchWrapper for .NET and I saw this:

[DllImport (SoundTouchDLLName)]
internal static extern void soundtouch_getVersionString2 (StringBuilder versionString, int bufferSize);    

And in the header file from the orginal C++ library:

__declspec(dllimport) void __stdcall soundtouch_getVersionString2(char* versionString, int bufferSize);

Where can I read about how it works? How StringBuilder passed to this function is filled with data?

Upvotes: 2

Views: 2301

Answers (1)

RomCoo
RomCoo

Reputation: 1893

The called libraray expects a pointer to a char-array with the size of bufferSize to write the text to.

soundtouch_getVersionString2(char* versionString, int bufferSize);

So you need a mutable object with predefined size that you can pass to the C++ library. Here the StringBuilder comes in place. Put it simple: since the usage of the memory of StringBuilder and the char-array is similiar, the caller can treat it as a char-array and fill it the common way.

Then use the function this way:

int bufferSize = 50;
StringBuilder versionString = new StringBuilder(" ", bufferSize);
soundtouch_getVersionString2(versionString, bufferSize);
string realString = versionString.ToString(); //convert it to unmutable stringstring

Upvotes: 2

Related Questions