Delphi 调用C# DLL(包含委托)

时间:2023-02-03 17:28:50

例子

C# Dll:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics; using System.Runtime.InteropServices; public delegate void ProcessDelegate(long ptr, long len); namespace TestDll
{ public interface ITestClass2
{ void YourProcedure();
void SetDelegate(long ptr);
} [ClassInterface(ClassInterfaceType.None)]
public class Class2 : ITestClass2
{
private ProcessDelegate delProcess = null; public void YourProcedure()
{
Debug.Print("enter");
if (this.delProcess != null)
{
byte[] test = System.Text.Encoding.Default.GetBytes("hello");
GCHandle hObject = GCHandle.Alloc(test, GCHandleType.Pinned);
IntPtr pObject = hObject.AddrOfPinnedObject();
this.delProcess(pObject.ToInt64(), test.Length);
if (hObject.IsAllocated)
hObject.Free();
}
Debug.Print("end");
} public void SetDelegate(long ptr)
{
IntPtr intPrt = new IntPtr(ptr);
delProcess = (ProcessDelegate)Marshal.GetDelegateForFunctionPointer(intPrt, typeof(ProcessDelegate));
} } }

注意的一点 一定要如下设置:

Delphi 调用C# DLL(包含委托)

另外, 如果需要导入其他库的话, 项目-->添加引用;

Delphi调用:

首先要注册dll,  命令行至C:\Windows\Microsoft.NET\Framework\v4.0.30319

运行 regasm "你的dll路径\名称.dll"

提示注册成功就可以使用这个dll了

uses ComObj;

procedure callBack(swide: Int64; size: Int64); stdcall;
begin
OutputDebugString(PChar(IntToStr(swide)+':'+ IntToStr(size)));
end; procedure TForm1.btn1Click(Sender: TObject);
var aClass: Variant;
begin
aClass:= CreateOleObject('TestDll.Class2');
aClass.SetDelegate(Dword(@call));
aClass.YourProcedure('test');
end;

示例: 下载地址