c# - native dll 的 .net 包装器 - 如何将运行时错误的风险降至最低?

标签 c# .net c++ dll wrapper

我正在开发 C# 应用程序。因为我有一些适用于 C/C++ 的最小二乘算法,翻译起来太麻烦了,所以我将 C++ 代码制作成一个 dll,然后在 C# 中创建了一个包装器。

在 C# 代码中,我定义了一个作为指针传递给非托管 C++ 代码的结构。该结构包含拟合函数的初始估计值,它还用于返回拟合结果。

在我看来,您必须在托管代码和非托管代码中定义结构。但是,将来使用我的源代码的人可能会决定更改 C# 应用程序中结构的字段,而不了解他们还必须更改 native 代码中的结构。这最多会导致运行时错误(更糟糕的是会产生错误结果),但不会有错误消息告诉开发人员/最终用户出了什么问题。

根据我的理解,不可能在非托管 C++ DLL 中创建一个测试来检查结构是否包含正确的字段,但是是否可以让 DLL 将正确格式的结构返回给 C# 包装器?

否则,有什么方法可以降低将来某些粗心的程序员导致难以检测的运行时错误的风险?

示例代码:

//C++
struct InputOutputStruct {
    double a,b,c;
}

extern "C" __declspec(dllexport) void DoSomethingToStruct(InputOutputStruct* s)
{

//... 算法

}

//C#
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
    public struct InputOutputStruct {
        public double a,b,c;
    }

[DllImport("CpluplusDll.dll")]
    public static unsafe extern bool DoSomethingToStruct(InputOutputStruct* s);

class CSharpWrapper {
    static void Main(string[] args)
    {
        InputOutputStruct s = new InputOutputStruct();
        unsafe {
            InputOutpustruct* sPtr = &s;
            DoSomethingToStruct(sPtr);
            s = *sPtr;
        }
    }
}

最佳答案

It appears to me that you must define the struct in both the managed and the unmanaged code.

不是真的。这就是 C++/CLI 的发明目的 - 促进更轻松地与 C++ 和 .NET 进行互操作。

关于c# - native dll 的 .net 包装器 - 如何将运行时错误的风险降至最低?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8397210/

相关文章:

c# - 将 aspx url 路由到 MVC Controller

c# - Windows 搜索服务器快捷版

c# - 刷新 WPF 中的 EF 数据绑定(bind)

c# - 程序不遵循 Windows 机器的日期格式(它可以在某处被覆盖吗?)

c++ - 对为什么这个主要不起作用感到困惑

c# - 接口(interface)和基类混合,正确的实现方式

c# - 中继器 databinder.eval 双引号

c# - 为什么 Entity Framework 将名为 "People"的表映射为我的 .edmx 文件中名为 "Person"的实体

c++ - 与 boost::property_tree XML 解析器一起使用时 boost::coroutine 库崩溃

c++ - 如何知道析构函数中的堆栈损坏来自何处?