Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting callback from C++ to C++/CX

In code I am porting I have this function which takes function as an argument:

void doSomething(std::function<void(std::string)> callback)

Could you please tell me how to implement this function in C++/CX, how to convert std::function to C++/CX delegate and how to call the callback later on from C++?

like image 287
Siegfried Avatar asked Jul 13 '26 00:07

Siegfried


1 Answers

Below is sample code, I am not sure if this is exactly what you are after - but maybe you will find some usefull code.

You can use delegates and events. To convert your function to delegate you can use proxy lambda. There are some usefull samples in msdn docs: Delegates (C++/CX)

public delegate void CallbackFunction(Platform::String^ arg);
public ref class MyCallbacks sealed {
public:
    event CallbackFunction^ callbackEvent;

    void doSomething(Platform::String^ arg) {
        callbackEvent(arg);
    }

internal:
    void doSomething(std::function<void(std::string)> callback) {
        CallbackFunction^ callbackPtr = ref new CallbackFunction(
            [=](Platform::String^ arg) {
            std::wstring tmp(arg->Data());
            std::string astr(tmp.begin(), tmp.end());//use wcstombs, MultiByteToWideChar, if such conversion is required
            callback(astr);
        });
        callbackEvent += callbackPtr;
    }
};

void test() {
    // On c++/cx side MyCallbacks initialization
    MyCallbacks^ cb = ref new MyCallbacks();

    // Here register callback functions to be raised later on
    cb->doSomething([](std::string s) {
        s.data();
    });

    // Raise callbacks from pure c++ inside c++/cx using delegetes and event
    cb->doSomething(L"DoSomething");
}
like image 83
marcinj Avatar answered Jul 15 '26 12:07

marcinj