How to manage memory correctly when using COM objects in VB?

Can someone explain how memory allocation / allocation occurs when passing values ​​between a COM object and VB.

My problems: 1.

IMyInterface::Method1 ([in] BSTR* pVal, [in] SAFEARRAY(BSTR)* pArray); 

Is it necessary to free allocated memory for the above parameters inside the COM object?

2.

 IMyInterface::Method2 ([in, out] BSTR* pVal); 

In this case, will VB take care of freeing memory for returned COM values? (The COM object allocates memory for these return values)

3.

 IProxy_MyInterface::Event1 ([in] BSTR* pVal); 

As soon as the event is processed inside VB, the allocation of memory for VB parameters will be canceled again?

Appreciate your help.

thanks

+4
source share
3 answers

Read the white papers ( Allocating and Releasing Memory for a BSTR ):

http://msdn.microsoft.com/en-us/library/xda6xzx7.aspx

Here is a description of all your cases.

+2
source

[in] parameters must be allocated by the caller and released by the caller, unless otherwise specified in the API documentation.

The [in, out] parameter is less clear, since it is BSTR * it is possible that the BSTR that you pass will be released and the other BSTR will be returned, so you must release the BSTR that is returning, and not the one you passed.

[out] and [out, retVal] , it means the transfer of ownership of memory, the function allocates memory, and the caller is responsible for freeing the memory.

For BSTR in C / C ++ COM, you must use SysAllocString and SysFreeString to place and release.

+1
source

VB6 has three cases of declaring string parameters - ByVal param As String , ByRef param As String and Function() As String . The first in the IDL corresponds to [in] BSTR param , the second to [in, out] BSTR *param , the third to [out, retval] BSTR *retval .

VB6 cannot declare [in] BSTR * , not [out] BSTR * params, but it can still use them, that is, it can call methods (in VC), which has parameters declared as out-only or in any other supported IDL way.

Also note that BSTR itself is a typedef'd pointer, something like wchar_t * , so BSTR * is actually wchar ** . The IDL needs a pointer for parameters, so you cannot declare [out] int param and [out] BSTR param also weird.

After [in] BSTR * confusion is clear (for the meaningless dual indirectness required for parameters, but not for input), the simple rule is that after you have * in the parameter declaration, the caller must release it after calling the method, if it is no longer NULL.

[in, out] SAFEARRAY(BSTR)* pArray displayed in ByRef pArray() As String in VB6, and you cannot change it to ByVal , that is * VB6 is required, so it cannot be in only one, and the caller must free safe array. This is not a safe array. Only

0
source

Source: https://habr.com/ru/post/1302645/


All Articles