【问题标题】:Can I load a DLL written in Delphi into PowerShell?我可以将用 Delphi 编写的 DLL 加载到 PowerShell 中吗?
【发布时间】:2017-11-10 13:49:52
【问题描述】:

我可以通过[Reflection.Assembly]::LoadFile() 方法直接在Powershell 中使用我在Delphi (Delphi 10) 中创建的DLL 吗?我目前正在尝试,但收到错误:

使用“1”个参数调用“LoadFile”的异常:“模块是 预计包含程序集清单。

我可以将 Delphi DLL 包装在我用 C# 编写的 DLL 中并以这种方式使用它,但我不希望这样做,因为这意味着每次更改都编译两个项目而不是一个。

这是我目前在 Delphi DLL 中的代码:

library TestDLL;


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

exports
  TestCall;

begin
end.

【问题讨论】:

  • 是的。但是你得到的错误是因为程序集清单。参考LINK
  • 我添加了一个带有 assembly 和 assemblyIdentity 元素的 TestDLL.manfiest 文件,它似乎没有任何效果。
  • 我猜你的 powershell 正在寻找一个托管程序集。您需要为此 dll 使用 pinvoke。 Websearch如何从powershell pinvoke

标签: powershell delphi dll


【解决方案1】:

您的 Powershell 代码适用于托管程序集。但是您的 Delphi 库是一个非托管 DLL。要直接访问它,请使用 pinvoke。一个简单的例子:

德尔福库

library TestDLL;

uses
  SysUtils;

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

exports
  TestCall;

begin
end.

使用上述库的 Powershell 脚本

$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);

现在,我真的不是 Powershell 专家,所以这可能是草率的。希望它能证明这一点。对于更复杂的参数类型,您将需要更高级的 Powershell 代码,但网络上有大量示例。

【讨论】:

  • Heffernam,这很好用,感谢您的帮助。
  • 仅供参考,PowerShell 代码中每行末尾的 ; 字符是多余的;如果你想在一行上执行多个命令,你真的只需要;
猜你喜欢
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 2011-01-16
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多