gpt4 book ai didi

c# - 将带有非托管导出的 C# DLL 中的字符串返回到 Inno Setup 脚本

转载 作者:行者123 更新时间:2023-12-02 03:31:51 26 4
gpt4 key购买 nike

我有一个 C# DLL,它使用 Unmanaged Exports 公开一个函数它由 Inno Setup Pascal 脚本直接调用。该函数需要返回一个字符串给Inno Setup。我的问题是我怎样才能做到这一点?
我的首选方法是将一个缓冲区从 Inno Setup 传递到 C# 函数,该函数将返回该缓冲区内的字符串。我想出了这段代码:

C# 函数:

[DllExport("Test", CallingConvention = CallingConvention.StdCall)]
static int Test([Out, MarshalAs(UnmanagedType.LPWStr)] out string strout)
{
strout = "teststr";
return strout.Length;
}

Inno 安装脚本:

function Test(var res: String):Integer; external 'Test@files:testdll.dll stdcall';

procedure test1;
var
Res: String;
l: Integer;
begin
SetLength(Res,256);
l := Test(Res);
{ Uncommenting the following line causes an exception }
{ SetLength(Res,l); }
Log('"Res"');
end;

当我运行此代码时,Res 变量为空(我在日志中看到“”)

如何从该 DLL 返回字符串?

请注意,我使用的是 Inno Setup 的 Unicode 版本。我也不想使用 COM 来调用这个函数,也不想在 DLL 中分配缓冲区并将其返回给 Inno Setup。

最佳答案

我建议您使用 BSTR 类型,该类型用于互操作函数调用的数据类型。在 C# 端,您可以将字符串编码为 UnmanagedType.BStr 类型,而在 Inno Setup 端,您可以使用 WideString,它与 BSTR 类型兼容。因此,您的代码将更改为以下内容(另请参阅非托管导出文档的 Marshalling sample 章节):

[DllExport("Test", CallingConvention = CallingConvention.StdCall)]
static int Test([MarshalAs(UnmanagedType.BStr)] out string strout)
{
strout = "teststr";
return 0; // indicates success
}

在 Inno Setup 方面,使用 WideString 来实现:

[Code]
function Test(out strout: WideString): Integer;
external 'Test@files:testdll.dll stdcall';

procedure CallTest;
var
retval: Integer;
str: WideString;
begin
retval := Test(str);
{ test retval for success }
Log(str);
end;

关于c# - 将带有非托管导出的 C# DLL 中的字符串返回到 Inno Setup 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20776847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com