DELPHI 调用C# DLL(包含委托)  
官方Delphi 学习QQ群: 682628230(三千人)
频道

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));

       }


   }


}

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


401221748811df4c547c980f0314b80c.png

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


 


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;



推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.042869091033936 seconds