问题描述
我有一个 C# DLL,它使用 非托管导出 由 Inno Setup Pascal 脚本直接调用.这个函数需要返回一个字符串给 Inno Setup.我的问题是我怎样才能做到这一点?
我的首选方法是将缓冲区从 Inno Setup 传递给 C# 函数,该函数将返回此缓冲区内的字符串.我想出了这个代码:
I have a C# DLL which exposes a function using Unmanaged Exports which is called directly by an Inno Setup Pascal script. This function needs to return a string to Inno Setup. My question is how can I accomplish this?
My preferred method is to pass a buffer from Inno Setup to the C# function which will return the string inside this buffer. I've come up with this code:
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
变量为空(我在日志中看到")
When I run this code the Res
variable is empty (I see "" in the log)
我怎样才能从这个 DLL 返回一个字符串?
How can I return a string from this DLL?
请注意,我使用的是 Unicode 版本的 Inno Setup.我也不想使用 COM 来调用这个函数,也不想在 DLL 中分配一个缓冲区并将其返回给 Inno Setup.
Note that I am using the Unicode version of Inno Setup. I also don't want to use COM to call this function nor to allocate a buffer in the DLL and return it to Inno Setup.
推荐答案
我建议您使用 BSTR
类型,用于互操作函数调用的数据类型.在 C# 方面,您将字符串编组为 UnmanagedType.BStr
类型,在 Inno Setup 方面,您将使用 WideString
,它与 BSTR
类型.因此,您的代码将更改为此(另请参阅 <代码>编组示例 Unmanaged Exports 文档的章节):
I would suggest you to use the BSTR
type, which is used to be a data type for interop function calls. On your C# side you'd marshall your string as the UnmanagedType.BStr
type and on the Inno Setup side you'd use the WideString
, which is compatible with the BSTR
type. So your code would then change to this (see also the Marshalling sample
chapter of the Unmanaged Exports docs):
[DllExport("Test", CallingConvention = CallingConvention.StdCall)]
static int Test([MarshalAs(UnmanagedType.BStr)] out string strout)
{
strout = "teststr";
return 0; // indicates success
}
在 Inno Setup 方面,使用 WideString
来实现:
And on the Inno Setup side with the use of WideString
to this:
[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# DLL 返回字符串到 Inno Setup 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论