【发布时间】:2020-06-19 22:01:43
【问题描述】:
是否可以通过引用将 int 从 C# 传递到 C++?
我在 C++ 中有一个简单的方法,它只增加一个数字并打印消息。
void ProcessOrder(int& num)
{
int start = num;
int stop = num + 10;
for (int i = start; i < stop; i++)
{
cout << "[Legacy] counting " << i << endl;
}
cout << endl;
// Note the above was original posted code and I made a stupid mistake and was never
// even changing `num` value passed by reference. The correct function to test
// should be as below (discard all of the above)
num = num + 5; // just modify the number to any value
}
现在我想从 C++/CLI 调用它,然后从 C# 调用它。
void StoreWrapper::ProcessOrder(int^ num)
{
LegacyStore* legacyStore = new LegacyStore();
legacyStore->ProcessOrder(num); // error here
}
但这会返回编译器错误:
error C2664: 'void LegacyStore::ProcessOrder(int &)': cannot convert argument 1 from 'System::Int32 ^' to 'int &'
我确保所有三个项目都是 x86,但错误仍然存在。价格方面,CLR 模块是 Win32,C# 控制台应用程序是 x86。
问题在这里:
如果我声明void StoreWrapper::ProcessOrder(int& num),那么这个方法可以编译,但现在我相信它是纯C++?我不能从 C# 端调用它,得到以下编译器错误:
error CS1503: Argument 1: cannot convert from 'int' to 'int*'
如果我将它声明为 `void StoreWrapper::ProcessOrder(int^ num)' 现在该方法甚至无法编译。
我尝试过使用System::Int32 变量类型但结果相同。
有没有办法通过引用将 int 从 .NET 世界传递给 C++?如果 C++ 端是 32 位,.NET 端是 64 位,是否可以?
更新
C#代码就到这里了,基本上我想在下面的代码中更新数字。
int number = 0;
Console.WriteLine("Original number = {0}", number);
store.ProcessOrder(ref number);
Console.WriteLine("After ProcessOrder number = {0}", number);
不幸的是,dxiv 的答案没有更新上面的数字。
【问题讨论】:
-
您需要使用
int%。与 int& 非常相似,但垃圾收集器可以跟踪它。 int^ 强制将 int 装箱,这是 C# 中不可用的功能(看起来像元数据中的 System.ValueType)。 -
@HansPassant 这绝对不是标记问题的重复。这个问题介于 .NET 和 C++ 边界之间,而不仅仅是在 C++/CLI 环境中通过引用传递,而这只是用 % 符号完成。
-
@zar “更新”下的最后一行说它仍然是“不更新”。还是这样吗?
-
@dxiv 我已经复制/粘贴了您的代码,但我将重新运行我可能遗漏的代码。明天更新。