1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
TMONWRAPP = Class(TOBJECT)
Private
Type
T_init = function(): Pointer; cdecl;
T_cleanup = procedure(const p_qpdf: Pointer); cdecl;
TMaFonction_Wrap = function (const TmonInstance: Pointer): TMonType; cdecl;
TMaProcedure_Wrap = procedure (const TmonInstance: Pointer; const Maval : TMonType); cdecl;
....
Public
constructor Create(const dllName: string = 'maddl.dll'); overload;
procedure Cleanup;
destructor Destroy(); override;
protected
fDLL_Handle: Cardinal;
fInstance: Pointer;
fError: Pointer;
...
Ma_function : TMaFonction_Wrap;
Ma_Procedure : TMaProcedure_Wrap;
cleanup: T_cleanup;
procedure Initialize;
procedure LoadFunction(var func: Pointer; const funcName: string);
end;
...
implemantation
procedure TMONWRAPP.SetProcedure(const Maval : TMonType);
begin
LoadFunction(@Ma_Procedure, 'set_MaProcedure');
Ma_Procedure(fInstance, Maval);
end;
function TMONWRAPP.MaFirstFonction: TMonType;
begin
LoadFunction(@Ma_function, 'Ma_function');
result := Ma_function(fInstance);
end;
procedure TMONWRAPP.LoadFunction(var func: Pointer; const funcName: string);
begin
if func = nil then
begin
func := GetProcAddress(fDLL_Handle, PChar(funcName));
if func = nil then raise Exception.Create(Format('Error loading function: "%s"', [funcName]));
end;
end;
procedure TMONWRAPP.Cleanup;
begin
if Assigned(fInstance) then
begin
LoadFunction(@cleanup, 'cleanup');
cleanup(@fInstance);
end;
end;
procedure TMONWRAPP.Initialize;
var
Init: T_init;
begin
Init := GetProcAddress(FDLL_Handle, PChar('init'));
if @Init = nil then raise Exception.Create('Error loading function: init');
fInstance := Init;
if (fInstance = nil) then Exception.Create('Could not init library!');
end;
constructor TMONWRAPP.Create(const dllName: String);
begin
fDLL_Handle := LoadLibrary(PChar(dllName));
if fDLL_Handle = 0 then raise Exception.Create('Error: Cannot find ' + dllName + #13#10#13#10 + SysErrorMessage(GetLastError));
Initialize;
end;
destructor TMONWRAPP.Destroy;
begin
if fDLL_Handle = 0 then Exit;
Cleanup;
FreeLibrary(fDLL_Handle);
inherited;
end; |