首页  编辑  

DLL的数据共享

Tags: /超级猛料/DLL.动态链接库/   Date Created:
library DllPrj;

uses
    SysUtils, Windows;

const
    CMapFileName = 'Kingron';

var
    // GlobalData: Integer = 100;
    PGlobalData: ^integer = @GlobalData;
    MapHandle: THandle;

function GetData: integer; stdcall;
begin
    Result := PGlobalData^;
end;

function SetData(const i: integer): integer; stdcall;
begin
    Result := PGlobalData^;
    if PGlobalData^ <> i then
        PGlobalData^ := i;
end;

procedure OpenShareData;
var
    size: integer;
begin
    size := SizeOf(PGlobalData^);
    MapHandle := CreateFileMapping(Dword(-1), nil, PAGE_READWRITE, 0, size, CMapFileName);
    if MapHandle <> 0 then
    begin
        PGlobalData := MapViewOfFile(MapHandle, FILE_MAP_ALL_ACCESS, 0, 0, size);
        if PGlobalData = nil then
            CloseHandle(MapHandle);
    end;
end;

procedure CloseShareData;
begin
    UnmapViewOfFile(Pointer(MapHandle));
end;

procedure DllEntryPoint(dwReason: Dword);
begin
    case dwReason of
        DLL_PROCESS_ATTACH:
            OpenShareData;
        DLL_PROCESS_DETACH:
            CloseShareData;
    end;
end;

exports
    GetData,
    SetData;

begin
    DllProc := @DllEntryPoint;
    DllEntryPoint(DLL_PROCESS_ATTACH);

end.