2013-12-15 77 views
0

我有一個C#dll,它是COM可見的並且具有事件處理程序委託。 在C#程序中使用它沒有問題,但我很難在C++中接收事件;從COM#可見的C#dll中獲取C++中的事件

這是C#代碼簡單的例子:

namespace TestCode 
{ 
    public delegate void DataReceivedHandler(object Sender, DataReceivedEventArgs e); 

    public sealed class DataValidator : IDisposable 
    { 


     public event DataReceivedHandler DataReceived; 

     private void OnDataReceived(DataReceivedEventArgs e) 
     { 
      Debug.WriteLine("### " + e.Value); 
      if (DataReceived != null) 
      { 
       DataReceived(this, new DataReceivedEventArgs(e.Status, e.Value, e.RejectedReason)); 
      } 
     } 

    } 


    public class DataReceivedEventArgs : EventArgs 
    { 

     public DataRecievedStatus Status { get; private set; } 
     public int Value { get; private set; } 
     public string RejectedReason { get; private set; } 

     public DataReceivedEventArgs(DataRecievedStatus status, int value, string rejectedReason) 
     { 
      this.Status = status; 
      this.Value = value; 
      this.RejectedReason = rejectedReason; 
     } 
    } 
} 

這是我如何使用它下面的C++例子:

#include <stdlib.h> 
#include <wchar.h> 
#include <windows.h> 

#using <mscorlib.dll> 
#using "TestCode.dll" 

using namespace System; 
using namespace System::Runtime::InteropServices; 
using namespace System::Collections; 
using namespace TestCode; 

namespace libTestCode { 
    public ref class Class1 
    { 
    public: 
     static DataValidator^ cc = nullptr; 
    }; 
} 

實現C++,你看到的問號。這是一個地方,我不知道如何實施它的權利:

#include "libTestCode.h" 

void init() 
{ 
    libTestCode::Class1::cc = gcnew DataValidator(); 

    libCashCode::Class1::cc->DataReceived += gcnew ????????? 

    return NULL; 
} 

將不勝感激任何幫助。

+0

訪問您當地的圖書館或書店以取得成功。你實際上並沒有使用C++,也沒有實際使用COM。 * static *的這種無償使用會讓你陷入很大的麻煩。 –

回答

0

原來,添加事件偵聽器幾乎一樣C#

只有實現C++文件應該編輯

void init() 
{ 
    libTestCode::Class1::cc = gcnew DataValidator(); 

    DataReceivedHandler ^handler = gcnew DataReceivedHandler(myHandler); 

    libCashCode::Class1::cc->DataReceived += handler; 

} 

void myHandler(Object ^obj, DataReceivedEventArgs ^eventArgs) 
{ 

} 

我的錯誤是,我忘了用「^」爲符號myHandler中的參數。