Invoke DLL procedure with variable argument amount lazarus / 21-General ---------------------------------------------------------------------- GreatCorn · 2022-07-29 10:04 Suppose I need to call a Windows DLL procedure. The thing is, I don't have the DLL path, proc name, and the corresponding procedure type at compile time. All of that is specified by the user at run time. Am I able to work with a single function type with only a const Arguments: Array of Variant/Pointer parameter and return type of Variant? I've been trying that approach and that only gave me errors (I tried SetConsoleTitle and GetStdHandle from kernel32, the first one gave a SIGSEGV, the second one gave a RunError(103) when I tried to WriteLn it directly and 0 when I assigned the result to a variable). Is it possible at all? ---------------------------------------------------------------------- MarkMLl · 2022-07-29 10:20 You might find the Dynlibs unit useful, but I suspect that in practice you'll (a) be restricted to simple types (avoid Pascal-style strings, dynamic arrays, variants and so on) and will find it easiest if you prepare a significant number of function/procedure wrappers rather than attempting to fudge a stack frame. Apart from that a great deal depends on the calling convention expected by the DLL entry points: at the very minimum you need to determine whether the DLL will discard the stack frame ("Pascal- style") or the caller does it ("C-style"). MarkMLl ---------------------------------------------------------------------- PascalDragon · 2022-07-29 13:04 Using the Rtti.Invoke function present in FPC 3.2.0 and newer this is indeed possible (with one known restriction, see below): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program tinvoke; {$mode objfpc}{$H+} uses  DynLibs, SysUtils, Classes, Windows, Rtti, TypInfo; const  TestString: AnsiString = 'Hello World'#13#10;var  sct, gsh: CodePointer;  lib: TLibHandle;  arg, res: TValue;  hs: THandleStream;begin  lib := LoadLibrary('kernel32.dll');  if lib = NilHandle then begin    Writeln('Failed to load kernel32.dll');    Halt(1);  end;   try    try      sct := GetProcAddress(lib, 'SetConsoleTitleA');      if not Assigned(sct) then        raise Exception.Create('Failed to load SetConsoleTitleA');      gsh := GetProcAddress(lib, 'GetStdHandle');    if not Assigned(gsh) then        raise Exception.Create('Failed to load GetStdHandle');       arg := TValue.specialize From('My Test Window');      res := Rtti.Invoke(sct, [arg], ccStdCall, TypeInfo(LongBool), True, False);      Writeln('Result: ', res.ToString);       arg := TValue.specialize From(STD_OUTPUT_HANDLE);      res := Rtti.Invoke(gsh, [arg], ccStdCall, TypeInfo(THandle), True, False);      Writeln('Result: ', res.ToString);       hs := THandleStream.Create(THandle(res.AsOrdinal));      try        hs.Write(TestString[1], Length(TestString));      finally        hs.Free;      end;    finally      FreeLibrary(lib);    end;  except  on e: Exception do begin      Writeln(e.ClassName, ': ', e.Message);    end;  end;   { so that we can see the new title applied }  Writeln('Done');  Readln;end. The restriction is as follows: as is this example currently only works on x86_64-win64, because only the Win64 calling convention as well as the i386 register calling convention are built in (on i386-win32 the Windows API uses stdcall); for everything else you need to add the unit FFI.Manager and provide the ffi library, however importing that on Windows does not yet work correctly with the unit as-is (on Linux it works). ---------------------------------------------------------------------- GreatCorn · 2022-07-30 19:10 Managed to find an article in Delphi here with the simplest usage of assembly. At first glance, the provided samples work fine. ---------------------------------------------------------------------- BobDog · 2022-07-31 10:59 Do it at compile time. Keep it easy. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  function  title(p:pchar):integer ; cdecl external 'kernel32.dll' name 'SetConsoleTitleA';  begin title('My title, Press return to end . . .'); readln; end. ---------------------------------------------------------------------- PascalDragon · 2022-07-31 11:35 Quote from: GreatCorn on July 30, 2022, 09:10:59 pmManaged to find an article in Delphi here with the simplest usage of assembly. At first glance, the provided samples work fine. This code is i386-win32 only. Quote from: BobDog on July 31, 2022, 12:59:07 pmDo it at compile time. Keep it easy. This might not be really feasable depending on the use case (e.g. a scripting system). Quote from: BobDog on July 31, 2022, 12:59:07 pmCode: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  function  title(p:pchar):integer ; cdecl external 'kernel32.dll' name 'SetConsoleTitleA';  begin title('My title, Press return to end . . .'); readln; end.  The calling convention for nearly all Windows API functions is stdcall, not cdecl. ---------------------------------------------------------------------- BobDog · 2022-07-31 12:09 OK, but it doesn't matter here. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  function  title(p:pchar):integer ;stdcall;varargs; external 'kernel32.dll' name 'SetConsoleTitleA'; function Printf(mask : pchar):integer; cdecl; varargs; external 'msvcrt.dll' name 'printf';    begin title('My title, Press return to end . . .',printf('%s %d %s',' hello',2022,' (middle of)')); readln; end. ---------------------------------------------------------------------- MarkMLl · 2022-07-31 12:21 Quote from: GreatCorn on July 30, 2022, 09:10:59 pmManaged to find an article in Delphi here with the simplest usage of assembly. At first glance, the provided samples work fine. Ignore the advice of a compiler developer at your peril, for they are subtle and quick to anger. MarkMLl ---------------------------------------------------------------------- PascalDragon · 2022-07-31 12:38 Quote from: BobDog on July 31, 2022, 02:09:39 pmOK, but it doesn't matter here. You're probably on x86_64-win64 then where there's only one calling convention anyway, cause the important difference between cdecl and stdcall is who does the cleanup and if you pick the wrong one you'll get a messed up stack (this might not even show with a simple program, but will lead to hard to debug errors in more complex situations). Quote from: MarkMLl on July 31, 2022, 02:21:56 pmQuote from: GreatCorn on July 30, 2022, 09:10:59 pmManaged to find an article in Delphi here with the simplest usage of assembly. At first glance, the provided samples work fine. Ignore the advice of a compiler developer at your peril, for they are subtle and quick to anger. Ignoring me... pff... their problem. Correcting me on the other hand despite me being the one who looked at the compiler's source and thus definitely knowing better? Oh boy... ---------------------------------------------------------------------- MarkMLl · 2022-07-31 12:59 Quote from: PascalDragon on July 31, 2022, 02:38:12 pmIgnoring me... pff... their problem. Correcting me on the other hand despite me being the one who looked at the compiler's source and thus definitely knowing better? Oh boy... Having discussed variadic parameter lists etc. with you in the past, and having hacked dynamic libraries since pretty much the day they were invented: you went to the trouble of telling OP about a new facility in the compiler which you believed would suit the problem he was describing, and at that point I think it would be very much in his interest to follow up your advice and if necessary discuss why things didn't quite fit the problem he described. Helping out by exercising a new compiler feature is to everybody's advantage. Expecting enthusiastic assistance for random code found online is excessively optimistic. MarkMLl ---------------------------------------------------------------------- GreatCorn · 2022-07-31 17:23 Quote from: MarkMLl on July 31, 2022, 02:21:56 pmIgnore the advice of a compiler developer at your peril, for they are subtle and quick to anger. I tested RTTI and tried to get familiar with it, looks like interesting stuff, so thanks a lot, will keep it in mind for x64. I presented the asm CALL way just as another approach for possible future searches, as I was too naive and forgot to look for Delphi code, so at first I was unable to find it. I didn't ask for assistance with it, just think of it as a sticky note. I'm not too experienced with Pascal (or programming in general), so I don't think of anything I do as the best method of solving a problem. I'm trying to get to know Windows and low-level stuff closer, in this instance just keeping it all at runtime. Quote from: BobDog on July 31, 2022, 02:09:39 pmCode: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  function  title(p:pchar):integer ;stdcall;varargs; external 'kernel32.dll' name 'SetConsoleTitleA'; function Printf(mask : pchar):integer; cdecl; varargs; external 'msvcrt.dll' name 'printf';    begin title('My title, Press return to end . . .',printf('%s %d %s',' hello',2022,' (middle of)')); readln; end. The varargs modifier is also something I didn't know about... Testing it with stdcall (though the docs say it's only for cdecl) proved that it works, but the DLL and proc name are supplied at compile time, which is what I avoid here. Quote from: MarkMLl on July 31, 2022, 02:59:00 pmvariadic parameter lists That's a great word to add to my vocabulary ---------------------------------------------------------------------- BobDog · 2022-07-31 19:24 You can do run time variadic also. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  uses dynlibs;   function Printf(mask : pchar):integer; cdecl; varargs; external 'msvcrt.dll' name 'printf'; type proc=function(x:pchar):integer;cdecl;varargs;  generic procedure check(x:T);  begin  if (qword(x)=0) then  begin  writeln('Failure to load, press return to quit');  readln;  halt;  end;  end;  var L:tlibhandle=0; title:proc; p:pointer=nil;  begin L:=loadlibrary('kernel32.dll');specialize check(L);  p:=getprocedureaddress(L,'SetConsoleTitleA');specialize check(p); title:=proc(p); title('My title',printf('%s','Press return to finish, thank you for testing . . .')); readln; end. ---------------------------------------------------------------------- MarkMLl · 2022-07-31 20:39 Quote from: GreatCorn on July 31, 2022, 07:23:48 pmthe DLL and proc name are supplied at compile time, which is what I avoid here. That's no problem, I've already pointed you at the standard library. However a parameter list specified entirely at runtime /will/ cause you problems, as will dynamic arrays or Pascal-style strings or variants. And the person who will be the most help to you is PascalDragon, so if he starts off by saying "look at such-and-such which has very recently gone into the development version of the compiler" you really should be taking notice. Apropos "variadic": "monadic" and "dyadic" have been around for a while, in particular in this https://en.wikipedia.org/wiki/APL_syntax_and_symbols#Monadic_functions way of categorising (what in Pascal or C we'd call) operators. However "variadic" seems to have crept in comparatively recently to describe (what in Pascal or C we'd call) functions with an arbitrary number of parameters, which I think is what you're asking about. I've discussed that sort of thing with Sven before,  and I think it's fair to say that the "take-home" is that even though C- with its customary calling convention- makes it look easy, when considering a modern compiler and its runtimes there's a lot going on under the surface. MarkMLl ---------------------------------------------------------------------- BobDog · 2022-08-01 22:36 Perhaps a safer runtime load. (Skip adding varargs and use an open array instead in a wrapper procedure) (Keep the imported  function parameter and return as it should be) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   uses dynlibs;    type proc=function(a:pchar):integer;cdecl;     procedure test(x:qword);  begin  if(x=0) then  begin  writeln('Failure to load, press return to quit');  readln;  halt;  end;  end;         function resize(cols:integer;lines:integer):pchar;  var  s:ansistring;  cs,ls:string;  begin  str(cols,cs);  str(lines,ls);  s:= 'MODE CON COLS='+cs+ ' LINES='+ls;  exit(pchar(s));  end;    procedure shell(a:array of integer);  begin  end;    var L:tlibhandle= 0; sys:proc=nil; p:pointer=nil; begin L:=loadlibrary('msvcrt.dll'); te st(qword(L));   p:=getprocedureaddress(L,'system'); test(qword(p));  s ys:=proc(p);  shell([sys('title My Title'),sys(resize(100,10)),sys('color 2f'),sys('echo Press return to end . . .')]);   readln; end.