从非托管功能触发事件

时间:2011-10-20 18:54:15

标签: events c++-cli managed

我试图使用指向托管对象的指针从非托管函数触发事件。我收到以下错误:

  

错误C3767:'ShashiTest::test::OnShowResult::raise':候选函数无法访问

我怎么能没有任何问题地调用常规函数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);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以通过手动定义事件并将raise()部分的访问级别更改为internalpublic来执行此操作。 (默认值为protectedprivate - 有关详细信息,请参阅http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/ff743ebd-dba9-48bc-a62a-1e65aab6f2f9处的ildjarn帖子。)

以下为我编译:

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;
};

另一种方法是定义一个可以触发事件的辅助函数。