2015-11-03 55 views
1

我已經設置了一個調用clr/dll來訪問一個MFC C++ dll並且適用於訪問MFC C++中的函數的控制檯模式程序DLL。但我想從c#中傳回一個委託函數,以便當MFC C++ dll中的某個函數需要調用c#程序時,它有回調函數來執行此操作。但我不能把它設置正確的...這是我的嘗試:傳遞一個委託函數回到一個clr dll,它調用c#中的一個mfc C++ dll#

的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(); 
     } 
    } 
} 

回答

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)); 
    } 
} 
+0

這工作,缺少的部分是爲extern「C」我曾試圖此以前,絕不會找到我的C++ DLL函數。 – quincy451

相關問題