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

例子

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调用:

首先要注册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;

示例: 下载地址

转载于:https://www.cnblogs.com/doorsky/p/4828301.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值