c# - 将 null 传递给 Interop 方法时,它会抛出 "Generic types cannot be marshaled."异常

标签 c# generics interop

我正在使用像这样导入的 C++ dll:

    [DllImport("Bank.dll"]
    static extern int GetDevice(byte versionCode, byte deviceAddress);

我可以像这样使用非空参数成功访问此方法:

    GetDevice(0, 3);

但是像这样用空参数调用这个方法:

    [DllImport("Bank.dll"]
    static extern int GetDevice(byte versionCode, Nullable<byte> deviceAddress);
    GetDevice(0, null);

给出以下运行时错误:

发生类型为“System.Runtime.InteropServices.MarshalDirectiveException”的未处理异常。 附加信息:无法编码“参数 #2”:无法编码通用类型。

如何将空参数成功传递给此方法?

最佳答案

我猜你弄错了Nullable<byte>相当于 C++ 的 unsigned char *或类似的。它不是。它实际上是一个 byte , 但其中的值也可以是 null .

如错误消息所述,您也不允许传递泛型类型,当然还有 Nullable<T>是泛型。因此,即使它在语义上意味着您想要的,也不会被允许。

但是根据您的问题“我如何成功地将空参数传递给此方法?”,这表明您真正处理的是指针类型作为参数类型。没有 complete code example不可能确定您的声明和用法应该是什么。但很可能您可以将参数声明为 byte[] ,并且 p/invoke 将正确编码它,包括将托管空引用映射到空指针。

即只需像这样声明您的方法:

[DllImport("Bank.dll"]
static extern int GetDevice(byte versionCode, byte[] deviceAddress);

默认编码应该适合您。如果不是,那么您需要编辑您的问题以包含您尝试调用的确切 C++ 声明。

关于c# - 将 null 传递给 Interop 方法时,它会抛出 "Generic types cannot be marshaled."异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27355241/

相关文章:

C# 泛型 : there is no way to constrain a type to have a static method?

c# - 您可以通过 C# 中的 Webclient 提供凭据吗?

c# - 在没有 Visual Studio 的情况下以编程方式创建解决方案/项目

java:将类作为依赖注入(inject)的参数传递

c++ - 在 C++ DLL 和 Cpp/CLI 控制台项目之间传输对象 vector

interop - GNU tar ././@LongLink "trick"到底是什么?

c# - 如何将 void* 转换为可在 C# 中使用的类型? C DLL 和 C# 之间的互操作性

c# - 为什么抛出异常时应用程序不会崩溃

java - 重构泛型

Java 泛型 - 太复杂?如何简化?