无法通过非托管导出返回自定义类型实例(Robert Giesecke) [英] can't return custom type instance with unmanaged export (Robert Giesecke)
问题描述
我正在使用RobertGiesecke的Unmanaged Exports Nuget包来导出.NET dll函数,以便在delphi5 win32应用程序中调用它. 传递和返回标准类型(字符串,整数...)时,一切工作正常. 但我尝试遵循编组样本( https://sites. google.com/site/robertgiesecke/Home/uploads#TOC-Marshalling-sample )返回C#中定义的自定义类型的实例,但我无法在delphi中正确访问该实例.
I am using RobertGiesecke's Unmanaged Exports Nuget package to export a .NET dll function in order to call it in a delphi5 win32 application. Everything is working perfectly when passing and returning standard types (string, int...). But I try to follow the Marshalling Sample (https://sites.google.com/site/robertgiesecke/Home/uploads#TOC-Marshalling-sample) to return an instance of a custom type defined in C# but I do not managed to access the instance in delphi correctly.
在Delphi中,我的代码是:
In Delp my code is:
type
TCreateSampleInstance = procedure(var sample: PSample); stdcall;
TSample = record
Name: WideString;
end;
PSample = ^TSample;
var
sample: PSample;
dllHandle: Cardinal;
proc4: TCreateSampleInstance;
begin
dllHandle := LoadLibrary('myDotNetAssembly.dll');
if dllHandle <> 0 then
try
@proc4 := GetProcAddress(dllHandle, PChar('CreateSampleInstance'));
if Assigned(proc4) then
begin
proc4(sample);
// how to access sample properties ?
Caption := sample^.Name; // Name = '' here instead of 'Test'...
end;
finally
FreeLibrary(dllHandle);
end;
end;
预先感谢您的帮助!
推荐答案
您可能还多了一层间接层.您拥有的Delphi代码封送了指向记录指针的指针.我希望C#代码会编组指向该记录的指针.我特别希望如此,因为要花大量精力来整理一个指向C#中记录的指针.
You've probably got an extra layer of indirection. The Delphi code you have marshals a pointer to a pointer to the record. I expect that the C# code marshals a pointer to the record. I expect this not least because it takes quite a bit of effort to marshal a pointer to a pointer to the record in C#.
我的猜测是C#代码是这样的:
My guess is that the C# code is like this:
public static void CreateSampleInstance(out Sample sample)
在这种情况下,您需要像这样编写所有内容:
In which case you need to write it all like this:
C#
public struct Sample
{
[MarshalAs(UnmanagedType.BStr)]
string Name;
}
[DllExport]
public static void CreateSampleInstance(out Sample sample)
{
sample.Name = "boo yah";
}
德尔福
type
TSample = record
Name: WideString;
end;
procedure CreateSampleInstance(out sample: TSample); stdcall;
external 'myDotNetAssembly.dll';
在Delphi方面,为简单起见,我使用加载时链接编写了该代码.如果您需要的话,您可以随时适应运行时链接.
On the Delphi side, I wrote it with load-time linking for simplicity. You can readily adapt to run-time linking if that's a requirement for you.
这篇关于无法通过非托管导出返回自定义类型实例(Robert Giesecke)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!