On 2005-07-08, Michael Tissington <mi*****@nospam.com> wrote:
I have a C++ function in a DLL of the form
BSTR WINAPI DoSomeWork(LPCSTR szConnection, LPCSTR szGUID)
I use SysAllocStringByteLen to return a BSTR.
For the most part this works accept when the calling applicaiton tries to
free the BSTR and I get a RtlFreeHeep error. I'm guessing because the bstr
has been allocated in one dll and it being released in another.
So how do I allocate the bstr that I'm returning ?
Ok... I believe to deallocate a buffer created with
SysAllocStringByteLen, that you need to deallocate that memory with
SysFreeString. Marshal.FreeBSTR will do this... What you may want to do
is wrap this call in a function that returns a managed string.
Maybe this would work... Though, I'm not sure since I haven't worked a
lot with BSTR in .NET.
Private Declare Function DoSomeWork Lib "whatever" _
(ByVal szConnection As String, _
ByVal szGuid As String) As IntPtr
Public Function DoSomeWorkWrapper _
(ByVal Connection As String, ByVal id As Guid) As String
Dim bstrPtr As IntPtr = IntPtr.Zero
Try
' you might need to manipulate the guid string some what,
' since I'm not sure what format your function needs it in :)
bstrPtr = DoSomeWork (Connection, id.ToString())
// return a managed string from the unmanaged bstr
Return Marshal.PtrToStringBSTR (bstrPtr)
Finally
If Not bstrPtr.Equals (IntPtr.Zero) Then
Marshal.FreeBSTR (bstrPtr)
End If
End Try
End Function
Anyway, that may or may not work. Otherwise, you'll need to pin the
object get the pointer, and then call FreeBSTR that way. But, anyway
you look at it - RtlFreeHeap probably can't deallocate the memory used
by the BSTR.
--
Tom Shelton [MVP]