zoukankan      html  css  js  c++  java
  • 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:WindowsMicrosoft.NETFrameworkv4.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;
    

    示例: 下载地址

  • 相关阅读:
    POJ1185:炮兵阵地(状压dp)
    POJ3254:Corn Fields(状压dp第一发)
    二进制x&(x-1);
    子集和问题(应用--换零钱)POJ2229:Sumsets
    JAVA math包
    UVA+POJ中大数实现的题目,持续更新(JAVA实现)
    HDU中大数实现的题目,持续更新(JAVA实现)
    SDUT中大数实现的题目,持续更新(JAVA实现)
    JAVA与ACM
    HDU3123:GCC(同余模简单题)
  • 原文地址:https://www.cnblogs.com/doorsky/p/4828301.html
Copyright © 2011-2022 走看看