2011-10-20 51 views
2

我正在嘗試使用指向託管對象的非託管函數觸發事件。我得到以下錯誤:從非託管函數中觸發事件

error C3767: 'ShashiTest::test::OnShowResult::raise' : candidate function(s) not accessible

我怎麼能沒有任何問題調用常規函數ShowMessage?

#pragma once 

#using<mscorlib.dll> 
#using<System.Windows.Forms.dll> 

using namespace System; 
using namespace System::ComponentModel; 
using namespace System::Collections; 
using namespace System::Diagnostics; 
using namespace System::Windows::Forms; 

namespace ShashiTest { 
    public delegate void ShowResult(System::String^); 

    public ref class test 
    { 
    public: 
     event ShowResult^ OnShowResult; 
     test(void) 
     { 
     }; 
     void ShowMessage() 
     { 
      MessageBox::Show("Hello World"); 
     } 
    }; 

    class ManagedInterface 
    { 
    public: 
     gcroot<test^> m_test; 
     ManagedInterface(){}; 
     ~ManagedInterface(){}; 

     void ResultWindowUpdate(std::string ResultString); 
    }; 
} 

void ShashiTest::ManagedInterface::ResultWindowUpdate(std::string ResultString) 
{ 
    if(m_test) 
    { 
     System::String ^result = gcnew system::String(ResultString.c_str()); 
     m_test->OnShowResult(result); 
    } 
} 
+0

這不是一個c + +的問題 –

+0

可能重複[C++/cli傳遞(託管)委託給非託管代碼](http://stackoverflow.com/questions/2972452/c-cli-pass-managed-delegate-to -unmanaged代碼) –

回答

1

可以通過手動定義事件,和改變raise()部分的訪問級別internalpublic做到這一點。 (默認或者是protectedprivate - 看到ildjarn後在http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/ff743ebd-dba9-48bc-a62a-1e65aab6f2f9瞭解詳情。)

以下編譯對我來說:

public ref class test 
{ 
public: 
    event ShowResult^ OnShowResult { 
     void add(ShowResult^ d) { 
      _showResult += d; 
     } 
     void remove(ShowResult^ d) { 
      _showResult -= d; 
     } 
    internal: 
     void raise(System::String^ str) { 
      if (_showResult) { 
       _showResult->Invoke(str); 
      } 
     } 
    }; 
    test(void) 
    { 
    }; 
    void ShowMessage() 
    { 
     MessageBox::Show("Hello World"); 
    } 
private: 
    ShowResult^ _showResult; 
}; 

另一種方法是定義一個輔助函數會開除事件。