[Delphi] DLL 만들기

Delphi 2009. 9. 5. 18:19



안 쓰니까 자꾸 까먹어서 적어둠...



* File > New > Other > Delphi Projects > DLL Wizard 선택하면 기본 DLL 프로젝트가 생성됨.
* 함수와 exports 선언을 통해서 DLL 제작가능


ex) Sum 이라는 함수를 가진 DLL
library MyLibrary;

uses
  Windows,
  SysUtils,
  Classes;

{$R *.res}

// 디버그 전용 프로시져
procedure D(s: String);
begin
  // Writeln(s);    // DOS
  OutputDebugString(PChar(s)); // 디버그
  // MessageBox(0, PChar(s), '', 0);
end;

// DLL 함수
function Sum(a, b: Integer): Integer;
begin
  Result:=a+b;
end;

exports
  Sum;

begin
end
.


위의 DLL을 가져다 쓰는 예제. (DLL 파일은 C:\MyProject\MyLibrary.dll 이라고 가정함)
만약 DLL 파일이 실행파일과 같은 위치에 있거나 OS PATH에 걸려있다면,
경로는 생략하고 DLL 파일명만 적어도 됨.


// 정적호출 방식
function Sum(a, b: integer) : integer; external 'C:\MyProject\MyLibrary.dll';

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Text:=IntToStr(Sum(1,2));
end;









// 동적호출 방식
procedure TForm1.Button1Click(Sender: TObject);
var
  hDLL: THandle;
  Sum: function (a, b: Integer): Integer;
begin
  hDLL:=LoadLibrary('C:\MyProject\MyLibrary.dll');
  if hDLL>=32 then begin
    @Sum:=GetProcAddress(hDLL, 'Sum');
    if @Sum<>nil then Memo1.Text:=IntToStr(Sum(1,2));
    FreeLibrary(hDLL);
  end;
end;

 






Posted by bloodguy
,