I am writing a C# DLL that I call from C++ using COM. It works well but though I try to follow the memory manipulation rules for this kind of usage, I am scared of not doing things the right way and have something like a memory leak.
My exposed C# functions all take structures as parameter, and each member of the structures are allocated and initialized by the C++ client. These members can be of 4 sorts :
Numerical values : they are just initialized, nothing more
LPSTRstrings : they are allocated with
CoTaskMemAlloc, and freed with
BSTRstrings : they are allocated with
SysAllocString, and freed with
SAFEARRAYarrays : they are allocated with
SafeArrayCreateEx, and freed with
SafeArrayDestroy. They are arrays of structures, and each "sub-structure" can include
BSTR, and even
SAFEARRAYSof structures... In this case, I don't call the free functions for these "sub-members" as the top
SafeArrayDestroydoes it itself as far as I know.
Then I have two kinds of usages :
"Sending" data. The exposed C# functions take a structure as input parameter. All the members are allocated by the client, then the function is called, and finally the free functions are called (as explained before)
"Receiving" data. The exposed C# functions take a structure as output parameter. In this case, the C++ client doesn't allocate the members of the structures as I assume the C# DLL does it itself. I only set the member to "NULL" value. But after the call of the function, I call the free functions.
So my question is simple : Do you see anything chocking in my way of doing things? Any bad usage? I have tried to follow all the rules that I was able to pick from the Microsoft documentation, but I have to admit that I am not confident with all this.
I will share some code as an answer to my post ;)