I'm trying to marshal a delegate to a function pointer. The return type of the delegate is an array of strings while the return type of the function pointer is a char**
The code below throws Invalid managed/unmanaged type combination exception. How do I solve this?
// unmanaged code
typedef char** (*MyFuncPtr)(void);
class __declspec(dllexport) MyUnmanagedClass{
private:
MyFuncPtr mFunPtr
public:
MyUnmanagedClass(MyFuncPtr funPtr)
{
mFunPtr = funPtr;
}
char* Func1()
{
// callback
mFunPtr();
return "something";
}
};
// managed wrapper (CLI)
public delegate cli::array<String^>^ MyDelegate();
public class MyCliClass{
private:
MyDelegate mDel;
public:
MyCliClass(MyDelegate del)
{
mDel = del;
}
String^ Func2()
{
MyFuncPtr funPtr = static_cast<MyFuncPtr>(Marshal::GetFunctionPointerForDelegate(mDel).ToPointer());
MyUnmanagedClass* muc = new MyUnmanagedClass(funPtr);
char* retValPtr = muc->Func1();
return context->marshal_as<String^>(retValPtr);
}
};
// managed client (C#)
class Program
{
static void Main( string[] args )
{
MyCliClass mcc = new MyCliClass(Func3);
mcc.Func2();
}
static string[] Func3()
{
return new[] { "Some 1", "Some 2" };
}
}
GetFunctionPointerForDelegate
. C++/CLI doesn't need it, because C++/CLI code can call both C++ and C# functions and access both C++ and C# objects directly. So what you need is a C++/CLI function with the right call signature so you can take a pointer to it and immediately get the right type (no casting!). Inside that function you can access C# objects, call delegates, whatever you need to do. – Ben Voigt