Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention for passing BSTRs into COM functions from C# (COM interop)

I am writing writing an API in COM in C++, and also writing a program which consumes this API in C#. My question is about BSTR memory management semantics when passing BSTRs into COM functions. Say my IDL looks like:

HRESULT SomeFunction([in] BSTR input);

Currently this function is implemented like this:

HRESULT SomeFunction(BSTR input) {
    // Do stuff ..., then:
    SysFreeString(input);
}

When I call it from C# with something like SomeFunction(myString), will C# generate something like this (pseudocode):

myString = SysAllocString("string");
SomeFunction(myString);

Or rather like this:

myString = SysAllocString("string");
SomeFunction(myString);
SysFreeString(myString);

That is, does C# free the BSTR that it generates to marshal to the COM interface, or should I free it inside my function? Thanks!

like image 830
fyhuang Avatar asked Aug 11 '11 21:08

fyhuang


1 Answers

From Allocating and Releasing Memory for a BSTR:

When you call into a function that expects a BSTR argument, you must allocate the memory for the BSTR before the call and release it afterwards. ...

So don't free it if it is an input parameter. C# (and any other runtime that uses COM objects) must respect the COM convention for managing memory pass in and out of COM objects, and must therefore manage the memory for the string if it is an input parameter. Otherwise, how would a COM object know that it is being called from C# or some other language runtime?

Additional google-fu turned up this: Marshaling between Managed and Unmanaged Code

... Regarding ownership issues, the CLR follows COM-style conventions:

  • Memory passed as [in] is owned by the caller and should be both
    allocated by the caller and freed by the caller. The callee should
    not try to free or modify that memory.
  • Memory allocated by the callee and passed as [out] or returned is owned by the caller and should be freed by the caller.
  • The callee can free memory passed as [in, out] from the caller, allocate new memory for it, and overwrite the old pointer value, thereby passing it out. The new memory is owned by the caller. This requires two levels of indirection, such as char **.

In the interop world, caller/callee becomes CLR/native code. The rules above imply that in the unpinned case, if when in native code you
receive a pointer to a block of memory passed to you as [out] from
the CLR, you need to free it. On the other hand, if the CLR receives
a pointer that is passed as [out] from native code, the CLR needs to
free it. Clearly, in the first case, native code needs to do the
de-allocation and in the second case, managed code needs to do
de-allocation.

So the CLR follows the COM rules for memory ownership. QED.

like image 85
MSN Avatar answered Oct 20 '22 18:10

MSN