从具有非托管导出的C#DLL中返回一个字符串到Inno安装脚本 [英] Returning a string from a C# DLL with Unmanaged Exports to Inno Setup script
问题描述
我有一个C#DLL,它使用非管理导出由Inno Setup Pascal脚本直接调用。此函数需要返回一个字符串到Inno Setup。我的问题是如何完成这个?
我的首选方法是将缓冲区从Inno安装程序传递到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
类型,这是用于interop函数调用的数据类型。在C#方面,您可以使用 UnmanagedType.BStr
类型来编组您的字符串,而在Inno安装方面,您将使用 WideString
,它兼容 类型。所以你的代码会改为这个(另见 非管理导出文档的编组样本
章节):
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安装方面,使用 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安装脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!