Calling C# method from C++ code in WP8

倖福魔咒の 提交于 2019-11-30 03:40:27

By getting an object in C# code to implement a Windows RT interface, and passing down a reference to this object, it is possible to do all of the above with a bit of set-up (if I understand correctly - not sure about exactly what you want to do with your Dispatcher examples - you might want to wrap the Dispatcher on the C# side).

  1. Create a Windows Runtime component library.
  2. Define a public interface class in a C++/CX header for the C# to implement (C++ to call) (e.g. ICallback).
  3. Define a public ref class in a C++/CX header for the C++ to implement (C# to call) (e.g. CppCxClass).
  4. Add a method in CppCxClass that passes and stores an ICallback. (A C++ global variable is shown for consiseness, I recommend you review this to see if you can find a better place to store this in your code-base).

    ICallback^ globalCallback;
    ...
    void CppCxClass::SetCallback(ICallback ^callback)
    {
        globalCallback = callback;
    }
    
  5. Reference the WinRT library in your C# code.

  6. C# code: create an instance of CppCxClass using var cppObject = new CppCxClass().
  7. C# code: create a class which implements ICallback (e.g. CSharpCallbackObject).
  8. C# code: pass an instance of CSharpCallbackObject down to C++. E.g. cppObject.SetCallback(new CSharpCallbackObject()).

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

After a lot of headaches trying to figure out the required code, I think it's worth posting the final version here

C++/CX

//.h
[Windows::Foundation::Metadata::WebHostHidden]
public interface class ICallback
{
public:
    virtual void Exec( Platform::String ^Command, Platform::String ^Param);
};
//.cpp
ICallback ^CSCallback = nullptr;
void Direct3DInterop::SetCallback( ICallback ^Callback)
{
    CSCallback = Callback;
}
//...

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

C#

public class CallbackImpl : ICallback
{
    public void Exec(String Command, String Param)
    {
        //Execute some C# code, if you call UI stuff you will need to call this too
        //Deployment.Current.Dispatcher.BeginInvoke(() => { 
        // //Lambda code
        //}
    }
}
//...
CallbackImpl CI = new CallbackImpl();
D3DComponent.SetCallback( CI);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!