Callback Functions

When passing a function pointer for a managed function to an unmanaged API, a reference must be maintained to the delegate or it will be garbage collected. If you pass a pointer to your managed function directly, a temporary delegate will be created, and as soon as it goes out of scope (at the end of MyFunction in the example below), it is subject to garbage collection. Consider the following Delphi 7 code:

function MyFunction: Integer; begin

RegisterCallback(@MyCallback); end;

In order for this to work in a managed environment, the code needs to be changed to the following:

const

MyCallbackDelegate: TFNMyCallback = @MyCallback;

function MyFunction: Integer; begin

RegisterCallback(MyCallbackDelegate); end;

This will ensure that the callback can be called as long as MyCallbackDelegate is in scope.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment