Here's a question for any C# gurus out there. I've created a delegate in C# to pass out to unmanaged C as a function pointer. It works fine, but how can I explicitly make sure it doesn't get garbage collected? I can't use any Microsoft-specific interoperability stuff because the code needs to work with Mono. In fact, it does work with Mono because Mono must do garbage collection differently than Microsoft does; my main problem is preventing Microsoft from collecting the delegate before my unmanaged code is done with it. Right now I'm continually reassigning the callback function pointer in a loop in C#, but that's not very elegant.
Message of the Day:
Bored? You'll find something new to do at MindThrow! Be a pal and Digg the MindThrow launch announcement (only takes 30 seconds).
5 Comments
Leave a comment
The comment login system is acting strange. If you get an error message saying you aren't logged in when you are, just reload the comment page and try again. I'm trying to track this bug down, but it's not easy.












I think you can make the delegate "static readonly" and that should prevent garbage collection on it. See, for example, "Programming C#" by Jesse Liberty. It's one of the best books about C# on the market IMO.
AG: I don't see anything in the MSDN description saying that readonly affects garbage collection. Plus, I don't want it to be unwritable, and I don't want it to be set in a constructor or declaration. Also, can readonly be used for all reference types, or is it limited like const? The docs aren't that clear.
The easiest thing to do would be to define a static Hashtable or ArrayList in your class (using it as a singleton), then push the delegate into that structure at the time you pass it, and remove it when your C code is done. Holding a strong reference inside of a static collection should keep your delegate from being GC'd, since statics are never themselves GC'd unless manually dereferenced (via "= null"), as Allen was pointing out.
Cy: But my delegate is static on its own. I'll try putting it into a collection and see if it works.
OK, have you tried looking at the AsyncCallback Delegate topic in MSDN? In this case, the Mono code would have to callback into the C# code to indicate that it was done, but that sounds like it might work for you.