我看过很多关于这个主题的文章,但没有一篇能帮助我解决我的问题。本质上,我希望能够通过 C.L.I. 从 C# 中通过引用传递变量。包装到 C++ 库,修改变量,并在不使用返回值的情况下通过函数将其传回。
我目前的代码如下:
在 C# 中:
[DllImport("UtilitiesWrapper.dll", EntryPoint = "Increment", CallingConvention = CallingConvention.Cdecl)]
public static extern void _Increment(int number);
int value;
_Increment( value);
在 C.L.I.包装器:
extern "C" {
__declspec( dllexport) void __cdecl Increment( int& number);
};
void __cdecl Increment( int& number) {
NS_UtilitiesLib::Increment( number);
}
在 C++ 中:
namespace NS_UtilitiesLib {
static void Increment( int& number) {
++number;
}
}
它一直给我一个关于内存在 C.L.I. 结束时损坏的错误。我认为这是因为它无法理解如何将 C# 变量放入参数中的函数(当我单步执行 C.L.I. 它永远不会获取原始值)。在使用 DllImport 在 C# 中声明函数时,我尝试使用 [MarshalAs(UnmanagedType.I4)],但它仍然不起作用。
有人知道怎么做吗?
最佳答案
[DllImport("ImportDLL.dll")]
public static extern void MyFunction(ref myInteger);
据推测作者打算ref int myInteger
但重点是:使用ref
关键字。
关于c# - 从 C# 中通过引用传递,通过 C.L.I.到非托管 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19696459/