我想在我的 cocos2d-x 3.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++ 类),但我不知道如何添加引用,因为编译器提示未知标识符“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 而不是 windows,无法添加 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
关于c# - 在 cocos2d-x wp8-xaml 中从 c++ 代码调用 c# 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28364050/