Calling DLL with pointers in Delphi

I am new to Delphi. I have a DLL with the following exported function:

bool __stdcall MyFunction(char * name, int * index)  

This code that calls this DLL function in C ++ works fine:

typedef void (WINAPI * MyFunction_t)(char *, int *);
void main()
{
    HMODULE mydll = LoadLibrary(L"C:\\mydll.dll");
    MyFunction_t MyFunction = (MyFunction_t)GetProcAddress(mydll, "MyFunction");

    int index = 0;

    MyFunction("MyString", &index); 
}

I need to do the same in Delphi. Here is my code that does not work (MyFunction is called, but the index variable does not get the corresponding value). This is a snippet of code, so please ignore the clutter. Any input would be greatly appreciated!

type
  TMyFunction= function(name: PChar; var index_ptr: Integer): Boolean; stdcall;

var
  fMyFunction : TMyFunction;
  i : Integer;
  h: THandle;

begin
  Result := 0;
  h := LoadLibrary('c:\\mydll.dll');
  fMyFunction := GetProcAddress(h, 'MyFunction');
  if @fMyFunction <> nil then
  begin
    fMyFunction('MyString', i);
    Result := i;
  end;
  FreeLibrary(h);
end;
+3
source share
2 answers

First of all, I assume that you are using a C link with extern "C"if this function is defined in the C ++ translation block.

Delphi 2009 , , PChar wide .

ANSI C, :

type
  TMyFunction= function(name: PAnsiChar; var index: Integer): Boolean; stdcall;

C bool, , LongBool, , Delphi Boolean:

type
  TMyFunction= function(name: PAnsiChar; var index: Integer): LongBool; stdcall;

\ , :

h := LoadLibrary('c:\mydll.dll');

, LoadLibrary , , h - HMODULE, THandle, .

Delphi :

  if Assigned(fMyFunction) then
    fMyFunction('MyString', Result);

, .

, .

+2

STDCALL TMyFunction.

-5

Source: https://habr.com/ru/post/1787797/


All Articles