【发布时间】: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),那么将使用初始值 - 但数组中的值仍然可以替换方法。 -
从数组中读取值解决了我的问题。