Reputation: 7370
Let's assume there is a static .Net method
static void RegisterDelegate(Action<array<Object^>^>^ handler);
defined in some assembly we can't modify.
I do have the following code:
static void HandleCallback(Action<array<Object^>^>^ handler, NATIVE_CPP_TYPE *nativeObject){
//some code here
}
static void TestCall(NATIVE_CPP_TYPE *nativeObject){
//RegisterDelegate(??);
}
where NATIVE_CPP_TYPE
is some non-serializable and native-only type which can't be modified either.
A call to TestCall(ptrToObj)
should now create a delegate of type Action<array<Object^>^>
. This delegate should call HandleCallback
when invoked and pass both, its own argument (the Object array) and the pointer to the native Object which was originally passed the the TestCall
function. Therefore the pointer needs to be stored in some kind of closure.
Do you have any idea how this can be done? I thought about the System::Linq::Expressions
namespace, but afaik I can't encapsulate native objects in that kind of expression.
Thanks in advance!
Upvotes: 0
Views: 638
Reputation: 17444
As far as I know, in C++/CLI you can't do managed lambdas. Of course, you can just create your own class that stores the native type and then exposes a method to be used as the delegate:
public ref class ManagedClass
{
static void RegisterDelegate(Action<array<Object^>^>^ handler)
{
}
};
class NATIVE_CPP_TYPE
{
};
static void HandleCallback(array<Object^>^ handler, NATIVE_CPP_TYPE *nativeObject)
{
//some code here
}
public ref class HandleCallbackWithNativeType
{
NATIVE_CPP_TYPE * m_pNativeObject;
public:
HandleCallbackWithNativeType(NATIVE_CPP_TYPE *nativeObject)
{
m_pNativeObject = nativeObject;
}
void Execute(array<Object^>^ array)
{
HandleCallback(array, m_pNativeObject);
}
};
static void TestCall(NATIVE_CPP_TYPE *nativeObject)
{
// This type will act as your closure "capturing" nativeObject.
HandleCallbackWithNativeType ^ pHandler = gcnew HandleCallbackWithNativeType(nativeObject);
Action<array<Object^>^>^ handler = gcnew Action<array<Object^>^>(pHandler, &HandleCallbackWithNativeType::Execute);
}
It's not as convienent as the lambda syntax, but it does the job.
Upvotes: 2