Home > Software design >  DLL C import functions to Delphi
DLL C import functions to Delphi

Time:09-02

How do I access the functions of a C DLL in Delphi

NOMANGLE int CCONV OpenSSPComPort (SSP_COMMAND * cmd);

In documentation: OpenSSPComPort

Parameters: Pointer to SSP_COMMAND structure

Returns: WORD 0 for fail, 1 for success

I suspect I am wrong about this Pointer.

In Delphi I am attempting this:

type
  SSP_COMMAND=class
   BaudRate:integer;
   PortNumber:integer;
end;

type
 TOpenSSPComPort = function (sspc:SSP_COMMAND):Integer;stdcall;

    var nv11 : THandle;
    OpenSSPComPort:TOpenSSPComPort;

    procedure TForm1.FormCreate(Sender: TObject);
    begin

    if nv11 = 0 then
    begin
      nv11 := LoadLibrary(pchar('ITLSSPProc.dll'));
      @OpenSSPComPort:=GetProcAddress(nv11, 'OpenSSPComPort');

      ss_cmd := SSP_COMMAND.create;

    end;
  end;

  procedure TForm1.Button1Click(Sender: TObject);
  begin
    ss_cmd.BaudRate := 9600;
    ss_cmd.PortNumber :=8;

   If OpenSSPComPort(ss_cmd)=0 Then
   Memo1.lines.add('Error OpenSSPComPort')
   else
   Memo1.lines.add('OpenSSPComPort - OK');

  end;

So result is : COM0 - Can't open this port but I sent 8 this means then SSP_COMMAND was sent incorrectly

CodePudding user response:

According to the C definition, you would need to change the following:

type
  SSP_COMMAND=packed record
    BaudRate:integer;
    PortNumber:integer;

    // according to https://github.com/phaer/Payout/blob/master/port_win32_ssp.h
    // there is another "ton" of fields defined which I do not enlist here
  end;
  PSSP_COMMAND = ^SSP_COMMAND;

type
  TOpenSSPComPort = function (sspc:PSSP_COMMAND):Integer;stdcall;

procedure TForm1.Button1Click(Sender: TObject);
var
  ss_cmd : SSP_COMMAND; 
begin
  ss_cmd.BaudRate := 9600;
  ss_cmd.PortNumber :=8;

  If OpenSSPComPort(@ss_cmd)=0 Then
    Memo1.lines.add('Error OpenSSPComPort')
  else
    Memo1.lines.add('OpenSSPComPort - OK');
end;

CodePudding user response:

This special library works like this: (may be useful to someone)

type
 SSP_COMMAND = class
   BaudRate:integer;
   PortNumber:byte;
   //... have more properties
end;

type
PSSP_COMMAND=^SSP_COMMAND;

type
 TOpenSSPComPort=  function (sspc:PSSP_COMMAND):Integer;stdcall;


var
  Form1: TForm1;
  nv11 : THandle;
  OpenSSPComPort:TOpenSSPComPort;
  ss_cmd:PSSP_COMMAND;

procedure TForm1.FormCreate(Sender: TObject)
begin

   nv11 := LoadLibrary(pchar('ITLSSPProc.dll'));
   @OpenSSPComPort:=GetProcAddress(nv11, 'OpenSSPComPort');
 
   New(ss_cmd);   
   ss_cmd^ := SSP_COMMAND.create;

end;

procedure TForm1.Button1Click(Sender: TObject);
begin
 ss_cmd.BaudRate := 9600;
 ss_cmd.PortNumber :=3;

   if OpenSSPComPort(pointer(ss_cmd))=0 Then
       Memo1.lines.add('Error OpenSSPComPort');
   else
       Memo1.lines.add('OpenSSPComPort - OK');

end;
  • Related