从cocos2d-x wp8-xaml中的c++代码中调用c#delegate

Call c# delegate from c++ code in cocos2d-x wp8-xaml

本文关键字:调用 c#delegate 代码 c++ cocos2d-x wp8-xaml 中的      更新时间:2023-10-16

我想在我的cocos2d-x3.3游戏(wp8-xaml后端)中从c++代码调用c#delegate。我发现:http://discuss.cocos2d-x.org/t/wp8-cocos2dx-and-xaml/4886/6

这是我在c++项目中的类"NativeEventHelper.cpp":

#pragma once
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
namespace PhoneDirect3DXamlAppComponent
{
public delegate void CallNativeFunctionDelegate();
public ref class NativeEventHelper sealed
{
public:
    NativeEventHelper(void);
    void SetCallNativeFunctionDelegate(CallNativeFunctionDelegate^ delegate) {
        m_CallNativeFunctionDelegate = delegate;
    }
    bool NativeEventHelper::CallNativeFunction()
    {
        if (m_CallNativeFunctionDelegate)
        {
            m_CallNativeFunctionDelegate->Invoke();
            return true;
        }
        return false;
    }
private:
    property static CallNativeFunctionDelegate^ m_CallNativeFunctionDelegate;
};
}
#endif

这是我在c#(MainPage.xaml.cs)类中的回调:

 public void CallNativeFunction()
    {
        Dispatcher.BeginInvoke(() =>
        {
            Debug.WriteLine("# NATIVE CODE #");
        });
        return;
    }

这里有一个问题。在构造函数中,我必须创建新的NativeEventHelper(来自c++类),但我不知道如何添加引用,因为编译器抱怨未知标识符"NativeEventHelp"。

 NativeEventHelper helper = new NativeEventHelper();
 helper.SetCallNativeFunctionDelegate(CallNativeFunction);

我还发现:从WP8 中的C++代码调用C#方法

这似乎完全一样,但我不知道如何引用这个类。这在我的情况下不起作用:https://software.intel.com/en-us/articles/using-winrt-apis-from-desktop-applications我在参考中看到的不是windows,而是windows phone sdk,无法添加winrt。

我终于解决了!!

首先:我不得不将名称空间更改为cocos2d。此外,我不得不无视警告,只是进行彻底的清理和重建。之后它就工作了。为了调用c++中的代码,我想出了这个:

NativeEventHelper^ nativeEventHelper = ref new NativeEventHelper();
nativeEventHelper->CallNativeFunction();

修复了NativeEventHelper.cpp文件:

#pragma once
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
namespace cocos2d
{
    public delegate void CallNativeFunctionDelegate();
    public ref class NativeEventHelper sealed
    {
    public:
        NativeEventHelper(void);
        void SetCallNativeFunctionDelegate(CallNativeFunctionDelegate^ delegate) {
            m_CallNativeFunctionDelegate = delegate;
        }
        bool NativeEventHelper::CallNativeFunction()
        {
            if (m_CallNativeFunctionDelegate)
            {
                m_CallNativeFunctionDelegate->Invoke();
                return true;
            }
            return false;
        }
    private:
        property static CallNativeFunctionDelegate^ m_CallNativeFunctionDelegate;
    };
}
#endif