C++/CLI delegate as function pointer (System.AccessViolationException)

后端 未结 2 774
误落风尘
误落风尘 2021-02-12 16:45

I have been experimenting with C++/CLI delegates (as I am trying to make a .NET reference library), and I have been having the following problem.

I define a delegate in

2条回答
  •  生来不讨喜
    2021-02-12 17:02

    A function pointer created from a delegate is invisible to the garbage collector, and isn't counted during reachability analysis.

    From the documentation:

    You must manually keep the delegate from being collected by the garbage collector from managed code. The garbage collector does not track reference [sic] to unmanaged code.

    If the delegate is collected, the function pointer is left dangling, and your program will behave badly. An access violation is one of the more likely outcomes, but not the only possibility. If the memory that used to contain the native/managed trampoline is reused for some other data, the CPU could try to interpret it as instructions, which might mean just about anything.

    The solution is to keep the delegate reachable, for example via the C++/CLI gcroot class, which is a thin wrapper around .NET GCHandle.

提交回复
热议问题