tags:

views:

156

answers:

4

I have been using WPF for a few years now and don't have any experience with anything but managed code. I started writing an app that uses a lot of win32 interop and i started wondering if i was leaking memory or generally doing something stupid that i didn't know about... So i thought i would seek some advice!

Is there any gotchas/tips/tricks when using win32 calls inside managed code? I am mostly interested in memory/garbage collection but any other tips are welcome!

+4  A: 

There are no gotchas. You free all resources that you allocate (unless the documentation indicates that the call you make takes over the resource, relieving you from ownership), and that's all there is to it. GC doesn't enter into it at all.

As a tip, System.Runtime.InteropServices.SafeHandle is a stock helper class to use Win32 handles RAII-style.

Pavel Minaev
+3  A: 

Almost resource you allocate in Win32 has to be deallocated with the right API call, which is documented on the MSDN page for the allocation API.

This is an entirely manual process; garbage collection doesn't assist with this at all, although you can use SafeHandle or (last resort) finalizers.

At the very least, use IDisposable wrapper classes around any resources you allocate. In some cases, these already exist in Windows Forms.

You can use Perfmon or Task Manager to monitor the number of handles open in your process.

Daniel Earwicker
+1  A: 

The main problem with win32 interop is (obviously) Linux/Mac OS incompatibility(Mono won't be able to help you yet if you have P/Invokes to win32 libraries).

Apart from that, I'm not aware of any problems. Unless, of course, the function you're calling itself leaks memory.

luiscubal
+1  A: 

You have to be a bit careful if you need to call GetLastError to determine why a win32 call failed. This page provides a detailed description.

Alex Peck