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

Make calls between C++ and C# code

本文关键字:调用 之间 代码 c++      更新时间:2023-10-16

我打算将游戏移植到Windows Phone 8。cocos2d-x创建的Visual Studio项目有一个名为MyGameComponent的c++项目,它是一个名为MyGame的c#项目的依赖项。在MyGame中,cocos2d-x提供了一个LocalizedStrings.cs文件。我希望能够调用那个文件,这样我就可以使用本地本地化系统。我该怎么做呢?

我还想在其他功能中使用它,所以请不要建议其他方法来进行本地化。

我使用cocos2d-x v2.2.5.

你可以将委托从c#传递给c++组件。

在你的c++组件中,你将定义一个委托和一个方法调用来设置该委托,像这样:

public delegate Platform::String^ GetTranslatedStringDelegate();
public ref class Component sealed
{
  public:
  void SetDelegate(GetTranslatedStringDelegate^);
  private:
  Platform::Agile<GetTranslatedStringDelegate> m_delegate;
}

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

public string GetTranslatedString()
{
   return "translated string";
}
// elsewhere in your C# code
component.SetDelegate(GetTranslatedString);

然后在你的c++中,只要你需要得到一个翻译过的字符串,你就可以调用委托方法。

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

如果你正在使用Managed c++,那么你只需要在你的c++项目中添加c# dll作为参考。然后像往常一样调用你的c# Dll。

ManagedCSharp::ManagedClass::ShowValue();

其中ManagedCSharp是命名空间,ManagedClass是类,ShowValue是方法