例子
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;
示例: 下載地址