So my questions are: What are the alternatives (cross-platform) for Windows messaging? Can callbacks replace messages?
Yes, you can replace messages with callbacks.
Do other languages support object callbacks?
You should not use object methods as callbacks. Common practice in portable code is to use handles (call notification):
DLL source:
type THandle = LongWord; {$IF SizeOf(THandle) < SizeOf(Pointer))} {$MESSAGE Error 'Invallid handle type'} {$ENDIF} TCallback = procedure(const aHandle: THandle); cdecl; var gCallback: record Routine: TCallback; Obj: TObject; Info: string end; function Object2Handle(const aObj: TObject): THandle; begin Result:= THandle(Pointer(aObj)) end; function Handle2Object(const aHandle: THandle; out aObj: TObject): Boolean; begin if gCallback.Obj <> nil then if aHandle = Object2Handle(gCallback.Obj) then begin aObj:= gCallback.Obj; Result:= true; Exit // WARRNING: program flow disorder end; aObj:= nil; Result:= false end; procedure DoCallback(); begin if Assigned(gCallback.Routine) then gCallback.Routine(Object2Handle(gCallback.Obj)) end; procedure SetupCallback(const aCallback: TCallback); cdecl; begin gCallback.Routine:= aCallback; end; procedure DoSomething(const aHandle: THandle; out aInfo: string); cdecl; var O: TObject; begin if Handle2Object(aHandle, O) then aInfo:= Format('%s class object %s', [O.ClassName(), gCallback.Info]) end; procedure Test(); begin gCallback.Obj:= TStream.Create(); try gCallback.Info:= 'created'; DoCallback(); finally FreeAndNil(gCallback.Obj) end; gCallback.Obj:= TMemoryStream.Create(); try gCallback.Info:= 'will be freed'; DoCallback(); finally FreeAndNil(gCallback.Obj) end end; exports SetupCallback, DoSomething, Test;
Executable source:
procedure Cb(const aHandle: THandle); cdecl; const STUPID: THandle = 1; EQUALLY_STUPID = $DEAD; var S: string; begin DoSomething(STUPID, S); DoSomething(aHandle, S); DoSomething(EQUALLY_STUPID, S) end; begin SetupCallback(@Cb); Test() end.
Edited: Now you can’t shoot in the foot.
I believe other languages have different technologies as an alternative to messages?
The OS has several message alternatives. However, not many are really portable.
You can also use:
- sockets
- (IMO too big in this case?) Ready-made messaging system (my favorite 0MQ )
source share