Monday, December 18, 2006

Pre-allocated Strings in Win32 API

As a part time developer, I can say that I have nowhere near mastered C#. When I find something that took me quite a while to figure out I might as well post it here in hopes it will make someone else's life easier. My problem was calling a Win32 API from within C# (PInvoke) with a char* that needed to be pre-allocated. Example:

long JustATest (long handle, char * pPreallocatedText)

Normally in the scenario of char* I would simply pass a type of string. This works fine until the API needs the string to already be allocated. From my test, there was no way to get the call to succeed using:


 

[DllImport("sample.dll", EntryPoint = "JustATest")]

public static extern int JustATest(int handle, string text);

What I finally discovered (thanks to another blog) was that you can use a StringBuilder instead and just pre-allocate its size:

[DllImport("sample.dll", EntryPoint = "JustATest")]

public static extern int JustATest(int handle, StringBuilder text);

To make the call simply create a StringBuilder:

StringBuilder text = new StringBuilder(2000);

Than call the API.

int iResult = JustAtest(myHandle, text);

This seemed to work perfectly. Hope this helps someone.

Chris

No comments: