Can I load a DLL written in Delphi into PowerShell?

Viewed 970

Can I use a DLL that I created in Delphi (Delphi 10), directly in Powershell via the [Reflection.Assembly]::LoadFile() method? I'm currently trying, but getting the error:

Exception calling "LoadFile" with "1" argument(s): "The module was expected to contain an assembly manifest.

I am able to wrap the Delphi DLL in a DLL that I wrote in C# and use it that way, but would prefer not to, since it would mean compiling two projects for each change instead of one.

This is the code I currently have in the Delphi DLL:

library TestDLL;


procedure TestCall(foo: PChar); stdcall;
begin
end;

exports
  TestCall;

begin
end.
1 Answers

Your Powershell code is appropriate for managed assemblies. But your Delphi library is an unmanaged DLL. To access it directly use pinvoke. A bare bones example of such:

Delphi library

library TestDLL;

uses
  SysUtils;

function TestCall(foo: PChar): Integer; stdcall;
begin
  Result := StrLen(foo);
end;

exports
  TestCall;

begin
end.

Powershell script to consume above library

$signature = @'
[DllImport(@"C:\Desktop\TestDLL.DLL", CharSet=CharSet.Unicode)]
public static extern int TestCall(string foo);
'@;

$type = Add-Type -MemberDefinition $signature -Name Win32Utils -Namespace TestDLL -PassThru;

[int] $retval = $type::TestCall("test string");
Write-Host($retval);

Now, I'm really no Powershell expert, so this may be sloppy. Hopefully it proves the point. For more complex argument types you'll need more advanced Powershell code, but there are plenty of examples on the web.

Related