从C#调用Delphi函数需要使用P/Invoke(Platform Invocation Services)。P/Invoke是一种技术,允许托管代码(如C#)调用非托管代码(如Delphi)。以下是一个简单的示例,展示了如何从C#代码中调用Delphi函数:
library MyDelphiLibrary;
uses
System.SysUtils;
function Add(a: Integer; b: Integer): Integer; stdcall;
begin
Result := a + b;
end;
exports
Add;
这将创建一个名为MyDelphiLibrary.dll
的动态链接库,其中包含一个名为Add
的函数。
DllImport
属性声明要调用的Delphi函数。例如:using System;
using System.Runtime.InteropServices;
namespace MyCSharpProject
{
class Program
{
[DllImport("MyDelphiLibrary.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int Add(int a, int b);
static void Main(string[] args)
{
int result = Add(5, 3);
Console.WriteLine("5 + 3 = " + result);
}
}
}
这将从C#代码中调用Delphi的Add
函数,并将结果输出到控制台。
请注意,这个示例仅用于演示目的。在实际项目中,您需要根据实际需求调整代码,并确保正确处理异常和错误。
推荐的腾讯云相关产品:
产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云