0

I'm having trouble passing ref parameter from managed C++ wrapper to C# method from dynamically loaded library. Returning value of parameter is 0.

C# method

void method(ref int param)

C++/CLI wrapper invoking method with tracking reference

Assembly^ assembly = Assembly::LoadFrom(assemblyName);
Type^ type = assembly->GetType(typeName);
gcroot<Object^> instance = Activator::CreateInstance(type);
MethodInfo^ method = instance->GetType()->GetMethod(methodName);

System::Int32^% refParam = gcnew System::Int32;
method->Invoke(instance, gcnew array<Object^> { refParam });
//refParam value is 0
earthless
  • 11
  • 3
  • 2
    You should read updated value back from array passed to `Invoke` method. – user4003407 Sep 16 '18 at 19:30
  • I think I should be able to read refParam. Isn't tracking reference equivalent to C# ref? – earthless Sep 16 '18 at 19:34
  • 1
    No, it changes the way the method is called, not the type of the argument. Also get rid of gcroot. – Hans Passant Sep 16 '18 at 19:58
  • I'd suggest translating the c# code from [this answer](https://stackoverflow.com/a/8779751) to [How to pass a parameter as a reference with MethodInfo.Invoke](https://stackoverflow.com/q/8779731) into c++/cli. The relevant sentence seems to be *If it were a `ref` parameter (instead of `out`) then the initial value would be used - but the value in the array could still be **replaced** by the method.* – dbc Sep 16 '18 at 20:15
  • 1
    Reading value from array solved my issue. – earthless Sep 17 '18 at 16:43
  • @earthless - Then you can [answer your own question](https://stackoverflow.com/help/self-answer) if you want. – dbc Sep 17 '18 at 20:40

1 Answers1

1

I'm able to read updated value from array passed to Invoke method.

array<Object^>^ args = gcnew array<Object^> { refParam };
method->Invoke(instance, args);

int value = (int)args[0];
earthless
  • 11
  • 3