How should I call this particular dll function in Delphi 6

旧巷老猫 提交于 2019-12-24 11:59:30

问题


I am absolutely new at calling functions from DLLs (call it bad programming habits, but I never needed to).

I have this C++ dll (CidGen32.dll at https://skydrive.live.com/redir?resid=4FA1892BF2106B62!1066) that is supposed to export a function with the following signature:

extern "C" __declspec(dllexport) int GetCid(const char* pid, char* cid); 

What it should do is to get a 13 char string such as '1111111111118' and return a 20 char hash.

I have tried for the last couple of days to call this function in Delphi 6 but to no avail. I have desperately tried I guess 50+ combinations and I got quite close on one occasion but my computer froze and I lost all my effort. Since it was based on luck, I could not redo it anymore.

I am also aiming not to register the DLL, but rather place it in the same folder.

Anyway, the plan was to have something like this:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);

  function GenerateCID(Prm: string): string;
  var
    aCID: PAnsiChar;
    uCID: AnsiString;
    i: integer;
    Hbar: Thandle;
    GetCID: function (X: PAnsiChar; Y: PAnsiChar): integer; {$IFDEF WIN32} stdcall; {$ENDIF}
  begin
    ucid := '';
    hbar := LoadLibrary('CidGen32.dll');
    if Hbar >= 32 then
    begin
      @GetCID := GetProcAddress(HBar, 'GetCID');
      if Assigned(GetCID) then
      begin
        i := GetCID(pAnsiChar(prm), aCID);
        uCID := aCID;
      end;
      FreeLibrary(HBar);
    end
    else
    begin
      //ShowMessage('Error: could not find dll');
    end;
    result := uCID;
  end;

begin
  ShowMessage(GenerateCID('1111111111118'));
end;

end.

But it seems I am dead wrong.


回答1:


You are using the wrong name to import the function. Its name is GetCid but you are trying to import GetCID. Letter case matters when you call GetProcAddress. If that still doesn't result in the GetProcAddress call succeeding, double check the name with which the function is exported using a tool like Dependency Walker.

The function is cdecl so you should declare it like this:

GetCID: function(pid, cid: PAnsiChar): Integer; cdecl;

And the other problem is that you are responsible for allocating the buffer behind cid. You did not do that. Do it like this:

SetLength(uCID, 20);
i := GetCID(pAnsiChar(prm), pAnsiChar(uCID));

And delete the aCID variable. And that >32 error check is wrong, compare against 0.



来源:https://stackoverflow.com/questions/17580361/how-should-i-call-this-particular-dll-function-in-delphi-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!