1

我看过很多关于这个主题的文章,但没有一篇文章能帮助我解决我的问题。从本质上讲,我希望能够通过 C# 的引用传递变量,通过 CLI 包装器到 C++ 库,修改变量,并通过函数将其传递回而不使用返回值。

我目前拥有的代码如下:

在 C# 中:

[DllImport("UtilitiesWrapper.dll", EntryPoint = "Increment", CallingConvention = CallingConvention.Cdecl)]
public static extern void _Increment(int number);

int value;
_Increment( value);

在 CLI 包装器中:

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;
    }
}

它不断给我一个关于在 CLI 函数结束时内存损坏的错误,我认为这是因为它无法理解如何将 C# 变量放入参数中(因为当我单步执行 CLI 时它永远不会拾取原始价值)。在使用 DllImport 在 C# 中声明函数时,我尝试使用 [MarshalAs(UnmanagedType.I4)] ,但它仍然不起作用。

有谁知道如何使这项工作?

4

1 回答 1

1

我用谷歌找到了这个

[DllImport("ImportDLL.dll")]
public static extern void MyFunction(ref myInteger);

大概是作者的意图ref int myInteger,但重点是:使用ref关键字。

于 2013-10-31T00:48:55.807 回答