2

For ex. i have c# COM object with such function:

int GetString([In, Out, MarshalAs(UnmanagedType.LPStr)]ref string str)

then i'm calling int from c++ (in c++ COM object is used via #import keyword), in generated wrapper method is declared as:

GetString(LPSTR * str, long * retVal)

i'm calling it this way:

char myStr[40];
LPSTR buf = (LPSTR)myStr;
LPSTR pBuf = &buf;

pComObject->GetString(pBuf);

what is strange:

1) myStr is not filled, and buf value is changed (it doesnt the same with myStr after the call) so, i suppose that c# marshaller allocates new block of memory

2) if c# allocates memory so should i call free(buf); or not?

2 Answers 2

3

Yes, the client should release the memory. In this case, one should use the CoTaskMemFree function to free the received buffer. Since the buffer may not be allocated on the client's heap. CoTaskMemFree will call an appropriate deleter.

Sign up to request clarification or add additional context in comments.

Comments

2

Yes, I think that you do need to free the buffer in your C++ code after calling the GetString function.

According to the COM "Memory Management Rules", the caller (your C++ code) should free memory that is returned as an output parameter. In the case of an input/output parameter, the callee (the CLR and your C# code) may free the memory of the parameter that you passed in and then allocate new memory for the output value, and it is again the caller's responsibility to free that memory.

1 Comment

Upvoted! Good explanation, and I should have mentioned the rules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.