c# - 从 C# 中通过引用传递,通过 C.L.I.到非托管 C++

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

我看过很多关于这个主题的文章,但没有一篇能帮助我解决我的问题。本质上,我希望能够通过 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)],但它仍然不起作用。

有人知道怎么做吗?

最佳答案

我用了Google寻找this :

[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/

相关文章:

c++ - 是否可以在 c++11 中扩展 std::tie 以接受占位符?

c++ - 从列表中选择项目到其他列表的 Qt 实现(双列表、累加器、列表构建器、TwoListSelection ...)

php - Uncaught Error : Call to undefined function mysql_connect() - each time I run my php file it shows me this error

c# - 从 .NET SqlCommand 调用时 SQL Server 批量插入失败

c++ - 使用自己的类名来解析推断上下文中的类型

c# - 在构造函数中使用 IEqualityComparer 的通用集合

多次迭代后,来自 C 的 C# 回调莫名其妙地失败

c# - .NET 混淆 DLL : how can I protect my code?

c# - 带 Prism 区域适配器的 AvalonDock

c# - 换日更新问题