Saturday, October 25, 2003

Managed code gotcha's...

.NET Framework Security: Using Win32 and Other Libraries (Working with C#)

Just learned a little lesson when working with managed code and P/Invoke. If you are providing a delegate as a callback to a P/Invoke'd Windows API function, make absolutely sure you hold a reference to that delegate for as long as that Windows API needs to call it... ;-) Since the CLR doesn't track references to things that travel off into the unmanaged nether-world, it will blithely garbage collect your delegate. This promptly hangs your unsuspecting API out to dry (think RegisterClass and CreateWindowEx). The absolutely insidious thing about all this is that it will work.. for a while. So take my advice, the oven is hot; wear your oven mitts...

For all the time I've spent working with managed code, COM-interop, and P/Invoke, you'd think I'd know this stuff... But then again, I'm no Don Box, ChrisAn, or Lutz Roeder, et. al.... they've had the luxury of being exposed to this for a few more years ;-) Eventually, this stuff will seep through the several inches of solid rock and touch some grey-matter someplace...