2015-02-06 22 views
1

我想从cocos2d-x 3.3游戏(wp8-xaml后端)中的C++代码中调用c#委托。 我发现这一点: http://discuss.cocos2d-x.org/t/wp8-cocos2dx-and-xaml/4886/6从cocos2d-x中调用c#代码wp8-xaml

这是我的班 “NativeEventHelper.cpp” 在C++项目:

#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++类),但我不知道如何添加refence,因为编译器抱怨未知标识符“NativeEventHelper”。

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

我也发现了这一点: Calling C# method from C++ code in WP8

这似乎是完全一样的,但是又不知如何引用这个类。这不适用于我的情况:https://software.intel.com/en-us/articles/using-winrt-apis-from-desktop-applications而不是窗口我在参考中看到windows phone sdk并且不能添加winrt。

+0

您使用的是'PhoneDirect3DXamlAppComponent'命名空间? – 2015-02-08 07:53:36

+0

是的,我试过了,但它抱怨说找不到这样的命名空间。 – Makalele 2015-02-08 11:05:13

+0

您是否将C#项目的引用添加到C++项目中? – 2015-02-08 17:32:52

回答

1

我终于解决了!

首先:我必须将命名空间更改为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