I am wrapping a C++ library to be used from .NET. There are functions in the C++ API that return std::future
. I want to have the .NET proxy classes return System.Threading.Tasks.Task
.
I thought of adding a replacement method on the C++ side that would take in a function pointer in addition to the methods parameters. I could then start up a new thread (using std::async
for example) and have that wait on std::future::get
. Once std::future::get
returned I could call the passed in function pointer. On the C# side I would pass the a pointer to a function that would complete the returned Task. Something like:
Task CallCpp(int a, int b) {
TaskCompletionSource<int> tcs;
Action callback = () => tcs.SetResult(0);
IntPtr callbackPtr = Marshal.GetFunctionPointerForDelegate(callback);
CppMethod(callbackPtr, a, b);
return tcs.Task;
}
[DllExport]
external void CppMethod(IntPtr callback, int a, int b);
void CppMethod(void (*callback)(), int a, int b) {
std::future f = realmethod(a, b);
std::async([&]{ f.get; callback(); });
}
std::future realmethod(int a, int b);
(Yes, the code has memory management issues. It should be enough to get the idea across though)