I write most of my code in unmanaged languages such as Delphi and C/C++. Sometimes customers ask me to interface my code to their .net code in which case I create a dll for them.

A recurring thing is that I need to return string to .net.

There are many ways to do this of course but in all cases we need to manage memory: who will allocate the memory for the string and who is responsible for freeing it?

Windows API Method
Windows API often requires the caller to pass in an allocated buffer and it’s maximum size and returns the actual size. An example is the GetComputerName API:

A typical call to this API looks like this in .net (VB.NET example):

As you can see we need to allocate the string before the API call and set the correct length after the API call. For that reason I used the StringBuilder class because the regular .net string class does not have a way to change the string length.

BSTR Method

For this reason I prefer to use the BSTR type because it has much easier memory allocation and deallocation.

An example using ATL’s CString class in C:

And an example implementation in VB.NET:

Below an example in Delphi for the ReturnString implementation (VB code stays the same):

Note: In all examples I am not passing the string as the function return value because of compiler implementation differences regarding the calling convention for the return value. A good description can be found here on stackoverflow.