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++?
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With