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!
From Allocating and Releasing Memory for a BSTR:
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
So the CLR follows the COM rules for memory ownership. QED.