Search code examples
javac++winapijna

C++ and Win32: When do I have to release variables etc?


I am usually a Java programmer and my C++ days were over for at least 15 years. Now I use C++ to build me a bridge (dll) for some Win32 functions.

The question remains, when do I have to release strings etc optaining from Win32 calls?

For an example: User32.dll => WINUSERAPI UINT WINAPI RealGetWindowClassA(__in HWND hwnd, __out_ecount_part(cchClassNameMax, return) LPSTR ptszClassName, __in UINT cchClassNameMax);. It gives me a pointer to the class name and I just map it to char [] using JNA. Do I have to dispose it after I copied it?

Are there any hints which and what to release / dealloc / dispose (?) / delete / free?

[Update]

As already being point out by technomage this example was all about owning the buffer being handed over. But the general question is when do I have to dispose it and when not? Is there any syntax or hint I can follow?

To give you an additional example, getting an interface (ISomething) and getting one of its properties. Usually one hands over a double pointer (ppVariable) so it can write a pointer value as result of operation. On one occasion I saw an follow up call of SysFreeString following up. So I guess I have to free it after using it.

Any idea about this one? How to handle it?

Also I have never seen that a window handle gets disposed (at least not in my code). What is the rule for that?


Solution

  • You're passing a buffer to the native function and telling the size of the buffer. That allows the called function to copy data to your buffer without having to worry about allocating memory.

    You already own the buffer, so normal Java rules apply.

    BTW, if you need to use byte[] with -A functions and char[] with -W functions. That "out" parameter is defined with LPTSTR, so you need to choose your string type accordingly.