c# - 在 C++ 和 C# 代码之间进行调用

标签 c# c++ windows-phone-8 cocos2d-x c++-cx

我正在将我的游戏移植到 Windows Phone 8。由 cocos2d-x 创建的 Visual Studio 项目有一个名为 MyGameComponent 的 C++ 项目,它是名为 MyGame< 的 C# 项目的依赖项/强>。在MyGame中,cocos2d-x为您提供了一个LocalizedStrings.cs文件。我希望能够调用该文件,以便我可以使用 native 本地化系统。我怎样才能做到这一点?

我还想将其用于其他功能,因此请不要建议进行本地化的替代方法。

我使用的是cocos2d-x v2.2.5。

最佳答案

您可以将委托(delegate)从 C# 传递到 C++ 组件。

在您的 C++ 组件中,您将定义一个委托(delegate)和一个用于设置该委托(delegate)的方法调用,如下所示:

public delegate Platform::String^ GetTranslatedStringDelegate();

public ref class Component sealed
{
  public:
  void SetDelegate(GetTranslatedStringDelegate^);

  private:
  Platform::Agile<GetTranslatedStringDelegate> m_delegate;
}

然后在 C# 中,您可以创建一个与委托(delegate)签名匹配的函数,并将其传递给您的组件:

public string GetTranslatedString()
{
   return "translated string";
}

// elsewhere in your C# code
component.SetDelegate(GetTranslatedString);

然后,在 C++ 中,只要需要获取翻译后的字符串,就可以调用委托(delegate)方法。

编辑:我写了一篇关于此主题的博客文章 - http://robwirving.com/2014/07/21/calling-c-methods-c-winrt-components/

关于c# - 在 C++ 和 C# 代码之间进行调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24826921/

相关文章:

windows-phone-8 - 如何更改广告网络(在我的 Windows Phone 开发中心)关联的 pubCenter 帐号

c# - 将方法作为参数传递

c# - 必须在与 DependencyObject 相同的线程上创建 DependencySource

c# - 按键延迟

c# - WP8 游戏开发和 C#

windows-phone-8 - wp8 LonglistSelector AnimateTo

c# - 集合正则表达式过滤问题

c++ - 在 C++ 代码中查找悬空的 else

c++ - 跟踪循环中的最小值和最大值

c++ - 从 const 成员函数返回类成员的指针