79144562

Date: 2024-10-31 11:44:46
Score: 1
Natty:
Report link

If you call an unmanaged function and this function returns -before- the callback has been used. Then the garbage collector can reclaim the callback since as far as .Net is concerned : it doesn’t exist at all it can garbage collect it.

There’s multiple ways you can go about it.

  1. if your callback can be a static function then you can follow the unmanaged caller example.
  2. If it can’t be static, (say you have a bunch of runtime arguments). Then while the callback will not be garbage collected when pinvoked, it can be garbage collected -after- the function returns. The arguments you pass to the pinvoked function definitely can be collected as well. So if you got some state class passed as an argument, you need to preserve them from being garbage collected through a GCHandle.

Unfortunately it’ll be tough to debug without knowing what exactly has been garbage collected. I suggest creating a GCHandle to the delegate then freeing it after the delegate has been called if the delegate is a callback called.

Reasons:
  • Long answer (-0.5):
  • No code block (0.5):
  • Low reputation (1):
Posted by: Jean-Baptiste Zeller