2012-09-18 97 views
-1

以下是我在c#中的代碼...從C++傳遞參數到c#回調

這裏的回調函數僅在c#中實現。 我想從C++回調DLL

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Runtime.InteropServices; 


class Program 
{ 
    // [DllImport("C:/Users/kool/Documents/Visual Studio 2010/Projects/DLL/Debug/DLL.dll", CallingConvention = CallingConvention.Cdecl)] 


    static void Main(string[] args) 
    { 


     function1(function2); // i want thia function2 to be fetched from ++ dll 

    } 

    public delegate void fPointer(); // point to every functions that it has void as return value and with no input parameter 
    public static void function1(fPointer ftr) 
    { 
     fPointer point = new fPointer(ftr); 
     point(); 
    } 
    public static void function2() 
    { 
     Console.WriteLine("Bla"); 
    } 
} 

我會createa從那裏,我將發送函數2到

function1(function2); 

我怎麼能實現它一個dll?

回答

0

一種方法是將C#程序集導出爲類型庫,並將它從C++中使用,就像它是COM組件一樣。

在Visual Studio命令提示符中使用TlbExp.exe將C#程序集導出爲類型庫。然後用RegAsm.exe註冊類型庫。然後在C++代碼中使用#import指令來導入類型庫。您現在可以像使用COM類一樣使用C++中的C#類。

更多細節請參見:http://msdn.microsoft.com/en-us/library/ms172270.aspx

編輯:對不起,這是你想做的事:用C++從C#,或者使用C#從C++?

任何一個都是可能的。上面的鏈接解釋瞭如何從C++使用C#。這個解釋瞭如何在C#中使用C++:http://msdn.microsoft.com/en-us/library/z6tx9dw3.aspx

0

您可以發送指向受管.net函數的指針,並從未受影響的代碼(回調函數)中調用它。

這裏的細節http://habrahabr.ru/post/130690/(如果需要,使用谷歌翻譯它從俄羅斯,但你需要看看最後兩個代碼示例)。

同時檢查你的代碼中調用 - 它應該(在的DllImport屬性利用__ STDCALL在C代碼和CallingConvention = CallingConvention.Cdecl)符合在託管和非託管兩側。