【问题标题】:How does one invoke a method on a ref class instance through reflection which returns a native pointer?如何通过返回本机指针的反射调用 ref 类实例上的方法?
【发布时间】:2011-07-01 18:18:40
【问题描述】:

我正在尝试通过反射调用 ref 类实例上的方法,该方法返回本机指针。

示例引用类头:

public ref class MyRefClass : public IDisposable
{
public:

MyNativeType* GetNativeInstance();

//Rest of the header...
}

这是一个反射尝试失败的例子

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()
}

使用这个委托

delegate MyNativeType* GetNativeInvoker();

尝试创建委托时,即使对象是具有方法“GetNativeInstance”(如MyRefClass)的引用类的实例,绑定也会失败并显示ArgumentException。这个问题必须在编译时不知道obj的类型的情况下解决,除了它是Object^

【问题讨论】:

    标签: .net reflection delegates c++-cli


    【解决方案1】:

    问题是您没有使用反射。 Delegate::CreateDelegate() 只允许在委托类型上使用,你的不是。使用Reflection修复,Type::GetMethod()返回一个方法。像这样(减去清理):

    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());
        }
    };
    

    【讨论】:

    • 谢谢,使用 MethodInfo 有效。我想我错误地假设 CreateDelegate 使用反射绑定到该方法。这里困扰我的主要事情是我认为 GetNativeInvoker 是一个委托类型。返回值和这个有关系吗?
    • 呃,当我编写代码时,这很有意义。不记得了。只要它有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多