5
votes

In C/C++ it is possible to create a DLL where some exports functions are forwarded to some other DLL (without using stub loader):

#pragma comment(linker, "/export:TestFunc=Real_Lib.dll.TestFunc")

Or a alternatively - using .def file:

EXPORTS
   TestFunc=c:/Real_Lib.dll.TestFunc

(notice lack of parameters or return type).

For example - in DependencyWalker for kernel32.dll - you can see this: KERNEL32.AddVectoredExceptionHandler => ntdll.AddVectoredExceptionHandler



Question: - can you achieve similar result for DLL in Delphi? (having to use CLI compiler is ok..)

Basically idea is generating DLL wrapper that overload only some functions, and forwards the rest - without having to create stub loader for all exported function (with parameters, return types, etc).



Note: I know that you can actually ommit method parameters for exported function that refers to import = big improvement..
But still need to specify correct method type (procedure/function), return type (for function) and calling convention.


Sample (TestProgram -> Forwarder -> Real_DLL):

Real DLL file - just your regular dll:

library Real_Lib;
function TestFunc(a, b: Integer): Integer; stdcall;
begin
  Result := a+b;
end;
exports TestFunc;
begin
end.

Forwarder DLL - "forwards" exported function to static import:

library Forwarder;
function TestFunc: Integer; stdcall; external 'Real_Lib.dll';
exports TestFunc;
begin
end.

= notice that parameters can be safelly omitted.
BUT - still requires specifying function return type.

Test program - uses forwarder DLL:

program TestProgram;
{$APPTYPE CONSOLE}
function TestFunc(a, b: Integer): Integer; stdcall; external 'Forwarder.dll';
begin
  Writeln('Result: ', TestFunc(2, 7));
  Readln;
end.


= This compiles and works: Result: 9.
Though DependencyWalker shows it as regular export that is simply calling import function:

And generates these opcodes:

00403E82    .  E8 7DFFFFFF       CALL <JMP.&Forwarder.TestFunc>

00403E04    $- FF25 20614000     JMP DWORD PTR DS:[<&Forwarder.TestFunc>]   ;  Forwarde.TestFunc

00383810 F>- FF25 08613800       JMP DWORD PTR DS:[<&Real_Lib.TestFunc>]    ; Real_Lib.TestFunc


So - is true forwarding some C/C++ only compiler magic or possible in Delphi too?

1
This is not really a feature of C or C++, but it is probably a feature of the Microsoft compiler. I doubt Delphi can do the same.Rudy Velthuis
I ended up splitting it in 2 parts: 1. DLL with Exports forwarders = C++ (VS), that has also custom function as stub dynamically loading and calling function from #2; 2. DLL in Delphi - providing custom function. Of course, implementing #2 in Delphi was simply to save time..megamurmulis

1 Answers

1
votes

Delphi cannot create such executables. You would need to perform some post-processing if you want to create such a DLL from Delphi.