I have a big problem because i dont understand how the pointers really work in delphi
First I take a function declaration from a dll.
FUNCTION:
type
TMICRCallback = function: Integer; stdcall;
Then I declare a Function in my code.
function CBMICRRead : Integer;stdcall;
The Function its really simple (This is an example)
function TCustomizedTenderPlugin.CBMICRRead : Integer; stdcall;
var
SUCCESS:integer;
begin
SUCCESS:=1;
Result:= SUCCESS;
end;
I declare a varible like this
Respuesta : TMICRCallback;
when i try to assign this variable to my function the problem happens 🙁
Respuesta := CBMICRRead;
This is my first time using pointers in delphi so maybe its a dumb question but please help me
TCustomizedTenderPlugin.CBMICRReadis an instance method. Which means that in order to call it you must have an instance on which to invoke it.On the other hand,
TMICRCallbackis a function pointer. It is compatible with plain functions rather than instance methods.They are simply not compatible. In order for
TCustomizedTenderPlugin.CBMICRReadto be compatible withTMICRCallbackyou need to define it as:The
of objectindicates that this type is compatible with instance methods. A variable of typeTMICRCallback(as defined in this answer) holds both a function pointer and an instance pointer. It is sometimes referred to as a two pointer function type.Before you proceed I recommend that you read carefully the documentation.
I note that you are using
stdcallcalling convention for these function pointers. This usually indicates that you are attempting interop with external modules. That’s not something that is reliable with instance methods. What I mean by this is that you cannot implement anof objectinstance method in a language other than Delphi. If this code is destined for use in an interop setting then you should refrain from usingof object.For an interop setting you would normally include the instance pointer as a separate parameter. In which case the Delphi declaration would look like this:
You would then implement such a function like this
Finally, the function in the external module that is passed the callback would need to be passed both
PluginCBMICRReadCallbackand the instance pointer for theTPlugininstance. Perhaps a little like this:which you would call like this:
Having looked at the C++ code at the related question it seems that the C++ side of the interface looks like this:
This callback doesn’t even admit a data pointer so you cannot use an instance method at all. Quite how you are meant to implement callbacks for multiple instances is beyond me! Anyway, you can declare this function in Delphi like this:
To call it you’ll need this: