我的 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/