【问题标题】:How to pass a ref parameter from managed c++ to c# method using reflection如何使用反射将 ref 参数从托管 c++ 传递到 c# 方法
【发布时间】:2018-09-21 11:03:54
【问题描述】:

我在将 ref 参数从托管 C++ 包装器传递到动态加载库中的 C# 方法时遇到问题。 参数返回值为0。

C#方法

void method(ref int param)

带有跟踪参考的C++/CLI 封装调用方法

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

【问题讨论】:

  • 你应该从传递给Invoke方法的数组中读取更新的值。
  • 我想我应该能够阅读 refParam。跟踪引用不等同于 C# ref 吗?
  • 不,它改变了调用方法的方式,而不是参数的类型。同时摆脱 gcroot。
  • 我建议将 c# 代码从 this answer 转换为 How to pass a parameter as a reference with MethodInfo.Invoke 到 c++/cli。相关句子似乎是 如果它是 ref 参数(而不是 out),那么将使用初始值 - 但数组中的值仍然可以替换方法。
  • 从数组中读取值解决了我的问题。

标签: c# c++-cli


【解决方案1】:

我能够从传递给Invoke 方法的数组中读取更新的值。

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

int value = (int)args[0];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2013-02-09
    • 2014-11-12
    • 1970-01-01
    • 2011-09-15
    相关资源
    最近更新 更多