Freigeben über


Calling C# code from C++ for Windows Phone apps and games

 

Calling C# code from C++ for Windows Phone apps and games

 

Often Windows Phone C++ developers get stuck when they need to call implemented C# functionalities in their C++ project. Especially, game developers working on Cocos2d-x and C++ need to call Facebook SDKs and In App Purchase (IAP) APIs which currently have only C# implementation for Windows Phone platform.

In this post, I am sharing steps to call C# code from C++ while building Windows Phone apps and games. C++/CX is not Managed C++, it’s a C++ component extension.

 

1. Create XAML and Direct3D apps for Windows Phone 8 for Cocos2d-x. Details: https://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207012(v=vs.105).aspx

 

2. Create a Windows Runtime component library.

 

3. Define a public interface class in a C++/CX header for the C# to implement (C++ to call) (e.g. ICallback).

 

4. Define a public ref class in a C++/CX header for the C++ to implement (C# to call) (e.g. CppCxClass).

 

5. Add a method in CppCxClass that passes and stores an ICallback. (A C++ global variable is shown for conciseness, you can use a better place to store this in your code-base).

 

ICallback^ globalCallback;

...

void CppCxClass::SetCallback(ICallback ^callback)

{

    globalCallback = callback;

}

 

6. Reference the WinRT library in your C# code.

 

7. C# code: create an instance of CppCxClass using var cppObject = new CppCxClass().

 

8. C# code: create a class which implements ICallback (e.g. CSharpCallbackObject).

 

9. C# code: pass an instance of CSharpCallbackObject down to C++. E.g. cppObject.SetCallback(new CSharpCallbackObject()).

 

You should now be able to call C# with globalCallback->CallCsharp(L"Hello C#");.  And you should be able to extend either ICallback and/or CppCxObject to do the rest of your tasks.

 

Code snippets:

C++/CX

//.h
[Windows::Foundation::Metadata::WebHostHidden]
public interface classICallback
{
public:
virtualvoidExec( Platform::String ^Command, Platform::String ^Param);
};
//.cpp
ICallback ^CSCallback = nullptr;
voidDirect3DInterop::SetCallback( ICallback ^Callback)
{
CSCallback = Callback;
}
//...

if (CSCallback != nullptr)
CSCallback->Exec( "Command", "Param" );

 

C# code

 

publicclassCallbackImpl : ICallback
{
publicvoidExec(StringCommand, StringParam)
{
//Execute some C# code, if you call UI stuff you will need to call this too
//Deployment.Current.Dispatcher.BeginInvoke(() => {
// //Lambda code
//}
}
}
//...
CallbackImpl CI = newCallbackImpl();
D3DComponent.SetCallback( CI);

 

 

Next, I will post on getting started with Cocos2d-x for Windows Phone and Windows Store games. Unity3D content will follow soon after Cocos2d-x

More on C++/CX https://msdn.microsoft.com/en-us/magazine/dn166929.aspx