2015-02-06 24 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