.net - How does one invoke a method on a ref class instance through reflection which returns a native pointer? -
i attempting invoke method on ref class instance through reflection, returns native pointer.
example ref class header:
public ref class myrefclass : public idisposable { public: mynativetype* getnativeinstance(); //rest of header... }
here example of failed attempt @ reflection
void invokethemethod(object^ obj) { mynativetype* mynative; getnativeinvoker^ del = (getnativeinvoker^) delegate::createdelegate(getnativeinvoker::typeid, obj, "getnativeinstance"); //get pointer , use if bind succeeds mynative = del(); //else handle case object not have getnativeinstance() }
using delegate
delegate mynativetype* getnativeinvoker();
when trying create delegate bind fails argumentexception
if object instance of ref class has method "getnativeinstance" (like myrefclass
). problem has solved without knowing obj's type @ compile time other fact object^
.
the problem not using reflection. delegate::createdelegate() allowed on delegate types, yours isn't one. use reflection fix, type::getmethod() returns method. (minus cleanup):
using namespace system; using namespace system::reflection; class mynativetype {}; public ref class myrefclass { mynativetype* instance; public: delegate void* getnativeinvoker(); myrefclass() { instance = new mynativetype; } mynativetype* getnativeinstance() { return instance; } static void test() { myrefclass^ obj = gcnew myrefclass; methodinfo^ mi = obj->gettype()->getmethod("getnativeinstance"); object^ result = mi->invoke(obj, nullptr); void* ptr = pointer::unbox(result); system::diagnostics::debug::assert(ptr == obj->getnativeinstance()); } };
Comments
Post a Comment