I want to call C# method in C++。I googled a lot about how to do this.
Now I do like this:
Use HelloCpp XAML project for test.It seems that create.py doesn’t create a xaml template?
And write Plus2SharpInterface.h、Plus2SharpDelegate.h、Plus2SharpDelegate.cpp in HelloCppComponent
Plus2SharpInterface.h
namespace Plus2Shap
{
namespace Plus2SharpInterfaceHelper
{
public interface class Plus2SharpInterface
{
void Leaderboard_Submit(Platform::String^ leaderboardKey, int score);
};
}
}
Plus2SharpDelegate.h
#pragma once
#include "Plus2SharpInterface.h"
namespace Plus2Shap
{
namespace Plus2SharpInterfaceHelper
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Plus2SharpDelegate sealed
// class Plus2SharpDelegate
{
public:
// Gets the single XLiveDelegate instance.
static Plus2SharpDelegate^ GetInstance();
// Set callback into the XLiveDelegate instance.
void SetCallback(Plus2SharpInterface^ callback);
// Gets or sets the callback.
property Plus2SharpInterface^ GlobalCallback;
private:
Plus2SharpDelegate();
static Plus2SharpDelegate^ m_Instance;
};
}
}
Plus2SharpDelegate.cpp
#include "Plus2SharpDelegate.h"
namespace Plus2Shap
{
namespace Plus2SharpInterfaceHelper
{
Plus2SharpDelegate::Plus2SharpDelegate()
{
}
Plus2SharpDelegate^ Plus2SharpDelegate::GetInstance()
{
if (m_Instance == nullptr)
{
m_Instance = ref new Plus2SharpDelegate();
}
return m_Instance;
}
void Plus2SharpDelegate::SetCallback(Plus2SharpInterface^ callback)
{
GlobalCallback = callback;
}
Plus2SharpDelegate^ Plus2SharpDelegate::m_Instance;
}
}
And write Plus2SharpImpl.cs in hellocpp(C# project)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Plus2Shap.Plus2SharpInterfaceHelper;
using System.Diagnostics;
public sealed class Plus2SharpImpl : Plus2SharpInterface
{
public void Leaderboard_Submit(string leaderboardKey, int score)
{
Debug.WriteLine("score:100");
}
}
And in App.xaml.cs,Init the delegate
Plus2SharpDelegate mPlus2SharpDelegate = Plus2SharpDelegate.GetInstance();
mPlus2SharpDelegate.SetCallback(new Plus2SharpImpl());
So that I can invoke the C# method in C++ like this
Plus2SharpDelegate^ m_XLiveDelegate = Plus2SharpDelegate::GetInstance();
m_XLiveDelegate->GlobalCallback->Leaderboard_Submit("abcd", 100);
But when i run the game,some error occured:
“System.TypeLoadException”type of exception occurred in unknown module .
“System.Reflection.TargetInvocationException”type of exception occurred in mscorlib.ni.dll
“System.Reflection.TargetInvocationException”type of exception occurred in System.Windows.ni.dll
The breakpoint stop at RootFrame_NavigationFailed method in app.xaml.cs.
I deleted the cs code and the invoke code in c++。
And I find the error will happen if Plus2SharpInterface.h、Plus2SharpDelegate.h 、Plus2SharpDelegate.cpp file exist。
How to solve it then?
Or some other method to call C# function in C++?