从 .Net 调用 Delphi 函数
Calling a Delphi Function from .Net
我正在尝试在 Delphi 中构建 DLL 并在 C# 中使用它。我有下面的简单代码
Delphi代码
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: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
您的 C# 声明与您尝试调用的 Delphi 函数几乎没有相似之处。回顾一下,目标是这样的:
function DelphiFunction(A: Integer; B: Integer; out outputInt: integer): integer; stdcall;
您的 C# 调用约定错误,return 值类型错误,并且缺少参数。你需要这个:
[DllImport("Project1.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int DelphiFunction(int a, int b, out int outputInt);
请注意,您不需要指定 CharSet
,并且 Delphi 中的 export
指令是虚假的并被忽略。删除它。
我正在尝试在 Delphi 中构建 DLL 并在 C# 中使用它。我有下面的简单代码 Delphi代码
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: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
您的 C# 声明与您尝试调用的 Delphi 函数几乎没有相似之处。回顾一下,目标是这样的:
function DelphiFunction(A: Integer; B: Integer; out outputInt: integer): integer; stdcall;
您的 C# 调用约定错误,return 值类型错误,并且缺少参数。你需要这个:
[DllImport("Project1.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int DelphiFunction(int a, int b, out int outputInt);
请注意,您不需要指定 CharSet
,并且 Delphi 中的 export
指令是虚假的并被忽略。删除它。