Michail
Michail

Reputation: 366

Using reflection Invoke

It is possible to call function with int* arguments using reflection Invoke?

My dream code:

Function for invoking:

long Invoked_Function(Int32, Int32*);

Invoking code

Int32 First_Parameter;
Int32 Second_Parameter;
Int32* Second_Parameter_Pointer = &Second_Parameter;
array<Object^>^ Parameters_Objects = gcnew array<Object^>(2){ First_Parameter, Second_Parameter_Pointer};
long Result = (long)Function_Type->Invoke(Class_Instace, Parameters_Objects);

It sying me about string "array^ Parameters_Objects = ..."

cannot convert from 'int *' to 'System::Object ^'

I can understand the reason.

And here is my question : it is possible to call the function with pointer to non-primiteve type as one of the arguments using Invoke function?

Upvotes: 1

Views: 95

Answers (1)

Hans Passant
Hans Passant

Reputation: 942000

That's accurate, there is no boxing conversion for a native pointer. Reflection will happily accept an IntPtr instead. A sample program that demonstrates this:

#include "stdafx.h"

using namespace System;
using namespace System::Reflection;

ref class Example {
public:
    long Invoked_Function(Int32 a, Int32* pb) {
        Console::WriteLine("Invoked with {0}, {1}", a, *pb);
        return 999;
    }
};

int main(array<System::String ^> ^args)
{
    auto obj = gcnew Example;
    auto mi = obj->GetType()->GetMethod("Invoked_Function");
    int b = 666;
    int* ptr = &b;
    array<Object^>^ arg = gcnew array <Object^> {42, IntPtr(ptr)};
    long result = (long)mi->Invoke(obj, arg);
    Console::WriteLine("Result = {0}", result);
    return 0;
}

Upvotes: 3

Related Questions