c# - Delphi dll函数转C#

标签 c# delphi pinvoke

对于已编译的 Delphi dll,声明的函数之一是

Mydll.dll

type
 TInfo = array [0..255] of byte;

type
 public
   function GetInfo(Memadr, Infolen: Integer): TInfo;

在 C# 中使用它的 DLLImport 格式是什么?

最佳答案

我会这样做:

德尔福

type
  TInfo = array [0..255] of byte;

procedure GetInfo(Memadr, Infolen: Integer; var Result: TInfo); stdcall;

C#

[DllImport(@"testlib.dll")]
static extern void GetInfo(int Memadr, int Infolen, byte[] result);

static void Main(string[] args)
{
    byte[] result = new byte[256];
    GetInfo(0, result.Length, result);
    foreach (byte b in result)
        Console.WriteLine(b);
}

您需要匹配调用约定。我选择了 stdcall,这是 P/invoke 的默认设置(这就是为什么它没有在 P/invoke 签名中指定)。

我会避免将数组作为函数返回值返回。以这种方式将其编码为参数会更容易。

事实上,一般来说,如果您想摆脱固定大小的缓冲区,您可以这样做:

德尔福

procedure GetInfo(Memadr, Infolen: Integer; Buffer: PByte); stdcall;

然后,要填充缓冲区,您需要使用一些指针算术或等效的东西。

关于c# - Delphi dll函数转C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6692177/

相关文章:

c# - 方法必须具有 InitializeComponent() 方法的返回类型

delphi - WinXP 和 Vista 上的兼容性

delphi - 如何在 Delphi IDE 中更快地创建自动属性?

C# 代码。适用于 win xp 不适用于 win 7

c# - LINQ查询优化

delphi - 如何获取TVirtualInterface的调用方法参数名称?

c# - 进程挂起从托管代码调用 AmsiScanBuffer

c# - 在通过 Wix 管理的自定义操作安装之前优雅地关闭应用程序

c# - 为什么不能在 C# 中将值隐式转换为字符串?