c# - 引用自身的编码类型

标签 c# c pinvoke marshalling

我的 C++ 代码中有以下(缩短的)函数定义:

EXPORT_API Table* OpenTableExport();

其中 Table 是以下形式的结构:

typedef struct Table
{
  int fCurrKey;
  int fTableNo;
  int fRecSize;
  char fCreating;
  Table* fNextTable;
  Table* fPrevTable;
  MyFileType fFile;
} Table;

因此,为了从托管代码中调用此函数,我自然尝试了以下操作:

[DllImport("Export.dll", EntryPoint = "OpenTableExport", CharSet = CharSet.Auto,   CallingConvention = CallingConvention.Cdecl)]
public static extern Table OpenTable();

具有以下表类:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class Table
{
    public KeyDescription fCurrKey;
    public int fTableNo;
    public uint fRecSize;
    public byte fCreating;
    public Table fNextTable;
    public Table fPrevTable;
    public FileDescription fFile;

}

现在使用该方法时,我收到以下异常(从德语翻译):

The field "fNextTable" of type "Table" can not be marshalled, no marshalling support exists for this type.

为什么 .NET 在任何情况下都无法编码其所编码的同一类型的 fNextTable 和 fPrevTable 成员?

我也可以用 IntPtr 替换托管类定义中的引用...但这真的有必要吗? (编码或多或少会起作用)。

最佳答案

通过以下方式定义结构:

public class Table
{
    public KeyDescription fCurrKey;
    public int fTableNo;
    public uint fRecSize;
    public byte fCreating;
    public IntPtr fNextTable;
    public IntPtr fPrevTable;
    public FileDescription fFile;
}

测试 IntPtr 成员是否为 NULL (IntPtr.Zero) 并处理它们。非托管 API 可能包含另一个需要 Table* 的函数。另请参阅用于托管-非托管内存交换的 Marshal.PtrToStructure 方法和另一个低级 Marshal 方法。

关于c# - 引用自身的编码类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25052256/

相关文章:

c - OpenCL 在没有输入数据或使用 3 维的情况下执行

c - GCC 4.8.1 编译时在 C99 代码中有许多宏和内联函数

c++ - 反向 P/调用教程?

C#缩短查询字符串参数

c# - 使用 Google API 恢复特定版本的电子表格

c# - 如何将扩展方法的 this 与 params 关键字结合起来?

c# - 如何将枚举从 View 传递到模型 ASP.Net MVC

c - 为什么我不退出这个 while 循环?

c# - 如何 P/调用分配并返回指向新数组的指针的函数

c# - 关于 C# 中的 DllImport