I am attempting to invoke a method on a ref class instance through reflection, which returns a native pointer.
Example ref class header:
public ref class MyRefClass : public IDisposable
{
public:
MyNativeType* GetNativeInstance();
//Rest of the header...
}
here is an example of a failed attempt at reflection
void InvokeTheMethod(Object^ obj)
{
MyNativeType* myNative;
GetNativeInvoker^ del = (GetNativeInvoker^) Delegate::CreateDelegate(GetNativeInvoker::typeid, obj, "GetNativeInstance");
//get pointer and use if bind succeeds myNative = del();
//else handle the case where the Object does not have GetNativeInstance()
}
using this delegate
delegate MyNativeType* GetNativeInvoker();
When trying to create the delegate the bind fails with ArgumentException even if object is an instance of a ref class that has the method “GetNativeInstance” (like MyRefClass). This problem has to be solved without knowing anything about obj’s type at compile time other than the fact it is an Object^.
The problem is that you are not using Reflection. Delegate::CreateDelegate() is only allowed on delegate types, yours isn’t one. Use Reflection to fix, Type::GetMethod() returns a method. Like this (minus cleanup):