gpt4 book ai didi

c# - 如何在 C# 的 delphi dll 中调用此函数

转载 作者:太空狗 更新时间:2023-10-30 00:45:14 25 4
gpt4 key购买 nike

我在 delphi 代码中定义了这个函数:

procedure TestFLASHWNew(
name: array of string;
ID: array of Integer;
var d1:double
); stdcall;

如何在 C# 中定义和调用它?

最佳答案

这是一个有点困惑的 P/Invoke,因为您不能(据我公认的有限知识)使用任何内置的简单编码技术。相反,您需要像这样使用 Marshal.StructureToPtr:

C#

[StructLayout(LayoutKind.Sequential)]
public struct MyItem
{
[MarshalAs(UnmanagedType.LPWStr)]
public string Name;
public int ID;
}

[DllImport(@"mydll.dll")]
private static extern void TestFLASHWNewWrapper(IntPtr Items, int Count, ref double d1);

static void Main(string[] args)
{
MyItem[] items = new MyItem[3];
items[0].Name = "JFK";
items[0].ID = 35;
items[1].Name = "LBJ";
items[1].ID = 36;
items[2].Name = "Tricky Dicky";
items[2].ID = 37;

IntPtr itemsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MyItem))*items.Length);
try
{
Int32 addr = itemsPtr.ToInt32();
for (int i=0; i<items.Length; i++)
{
Marshal.StructureToPtr(items[i], new IntPtr(addr), false);
addr += Marshal.SizeOf(typeof(MyItem));
}

double d1 = 666.0;
TestFLASHWNewWrapper(itemsPtr, items.Length, ref d1);
Console.WriteLine(d1);
}
finally
{
Marshal.FreeHGlobal(itemsPtr);
}
}

德尔福

TItem = record
Name: PChar;
ID: Integer;
end;
PItem = ^TItem;

procedure TestFLASHWNewWrapper(Items: PItem; Count: Integer; var d1: Double); stdcall;
var
i: Integer;
name: array of string;
ID: array of Integer;
begin
SetLength(name, Count);
SetLength(ID, Count);
for i := 0 to Count-1 do begin
name[i] := Items.Name;
ID[i] := Items.ID
inc(Items);
end;
TestFLASHWNew(name, ID, d1);
end;

我已经使用调用您的 TestFLASHWNew 函数的包装函数实现了它,但您无疑会想要重新处理它。

我假设您使用的是带 Unicode 字符串的 Delphi。如果不是,则将 [MarshalAs(UnmanagedType.LPWStr)] 更改为 [MarshalAs(UnmanagedType.LPStr)]

关于c# - 如何在 C# 的 delphi dll 中调用此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5967170/

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