You could return a BSTR and let the interop marshaling do clean up for you:
https://www.codeproject.com/Articles/1189085/Passing-strings-between-managed-and-unmanaged-code On Tue, 26 Nov. 2019, 11:09 Greg Keogh, <[email protected]> wrote: > > msg is a stack variable, you can't return it iirc. Either create a var on >> the heap, or pass msg in as a parameter. >> > > D'oh! You're right. I changed the code to the following and it's working. > Notice use of CoTaskMemAlloc, which I think is the least worst choice of > heap allocation functions according to the MSDN docs. > > Notice that I've completely forgotten what the lengths are supposed to be > for string lengths, is it x2 for wchar? is it correct to allocate 200 bytes > for 100 wchars? The compiler is giving me an overrun warning. You're > supposed to use sizeof or something like that, but my brain has gone mushy > on all those rules now (which is part of the reason I never want to code > this assembler crap again!). > > Even worse … what about the memory leak in CoTaskMemAlloc? I make the > buffer, copy in the string and return it, but it's now leaked. Should I use > a global static buffer that can be released later? When? > > *GK* > > [image: image.png] > > >
