将委托函数传递回clr dll,它在c#

时间:2015-11-03 15:10:50

标签: c#

我已经设置了一个c#控制台模式程序,该程序调用clr / dll来访问MFC c ++ dll,并且用于访问MFC c ++ dll中的函数。但是我想从c#传回一个委托函数,这样当MFC c ++ dll中的函数需要调用c#程序时,它就会有回调来执行该操作。但我无法正确设置......这是我的尝试:

Program.cs的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using dd_clr; // this is my clr.dll


namespace dd_gui
{
    public delegate int GUI_CallbackDelegate(string fn);

    class Program
    {

        int GUI_callback(string fn)
        {
            Console.WriteLine("Begin GUI_callback()");
            Console.WriteLine("GUI_callback fn=" + fn);
            Console.WriteLine("End GUI_callback()");
            return (1);
        }

        static GCHandle gch;

        static void Main(string[] args)
        {    

             Console.WriteLine("begin GUI");

             dd_clr.DDManaged instance = new dd_clr.DDManaged();

             GUI_CallbackDelegate ^ fp = gcnew              GUI_CallbackDelegate(GUI_Callback); // this does not compile for some reason ; expected after gcnew ???
             gch = GCHandle.Alloc(fp);

             instance.Set_GUICallback(fp); // this I am trying to get to work.
             instance.batch_run("test.dap"); // this call works.

             Console.WriteLine("end GUI");

             gch.Free();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

从您的代码来看,您尝试做的事情并不明显,但您可以通过这种方式将代理传递给C ++:

server.h:

extern "C"
{
    typedef int(__stdcall * ComputeCallback)(int);
    __declspec(dllexport) int Sum(ComputeCallback computeCallback);
}

server.cpp:

__declspec(dllexport) int Sum(ComputeCallback computeCallback)
{
    int sum = 0;
    for (int i = 0; i < 4; i++)
    {
        int x = computeCallback(i);
        sum += x;
    }
    return sum;
}

client.cs:

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate int ComputeCallback(int value);

class Program
{
    [DllImport("server.dll")]
    public static extern int Sum(ComputeCallback callback); 

    static void Main(string[] args)
    {
        ComputeCallback callback = x =>
        {
            Console.WriteLine("Computing. X = {0}", x);
            return x*x;
        };

        Console.WriteLine("Result: {0}", Sum(callback));
    }
}
相关问题