C#通过参考文献,通过C.L.I.到非托管C ++

时间:2013-10-31 00:40:31

标签: c# c++ dll static-libraries command-line-interface

我已经看过很多关于这个主题的文章,但都没有帮助我解决我的问题。本质上,我希望能够通过引用从C#传递变量到C.L.I.包装到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)],但它仍然不起作用。

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

1 个答案:

答案 0 :(得分:1)

我使用Google查找this

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

据推测,作者想要ref int myInteger,但重点是:使用ref关键字。