【问题标题】:Calling a Delphi Function from .Net从 .Net 调用 Delphi 函数
【发布时间】:2020-03-13 10:27:19
【问题描述】:

我正在尝试在 Delphi 中构建一个 DLL 并在 C# 中使用它。我有以下简单的代码 德尔福代码

library Project1;
uses
  System.SysUtils,
  System.Classes;

{$R *.res}

function DelphiFunction(A: Integer; B: Integer; out outputInt : integer): integer; stdcall; export;
 begin

     if A < B then
        outputInt := B
     else
        outputInt := A;

   DelphiFunction := outputInt;
 end;

exports DelphiFunction;
begin
end.

C#代码

[DllImport("Project1.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern bool
DelphiFunction(int a, int b);

private void button3_Click(object sender, EventArgs e)
{
   var a = 2;
   var b = 3;
   var result = DelphiFunction(a, b);
}

但是,我在 var result = DelphiFunction(a, b); 行遇到错误

System.AccessViolationException: '试图读取或写入受保护的内存。这通常表明其他内存已损坏。'

【问题讨论】:

    标签: .net delphi pinvoke


    【解决方案1】:

    您的 C# 声明与您尝试调用的 Delphi 函数几乎没有相似之处。回顾一下,目标是这样的:

    function DelphiFunction(A: Integer; B: Integer; out outputInt: integer): integer; stdcall;
    

    您的 C# 调用约定错误,返回值类型错误,并且缺少参数。你需要这个:

    [DllImport("Project1.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern int DelphiFunction(int a, int b, out int outputInt);
    

    请注意,您不需要指定CharSet,Delphi 中的export 指令是虚假的并被忽略。删除它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      相关资源
      最近更新 更多