如何将结构封送为指向结构的指针? [英] How do I marshal a structure as a pointer to a structure?
问题描述
我试图将结构从C#传递到C ++库.我将结构作为对象传递,C ++函数期望它作为指针(void *).
I am trying to pass a structure from C# into C++ library. I pass structure as an object, and C++ function expects it as a pointer (void *).
我在传递结构时遇到问题.
I am having problem passing the structure.
[DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr TheFunction([MarshalAs(UnmanagedType.LPStruct)] UserRec userRec);
这是我得到的运行时异常文本:
Here is the run-time exception text I get:
无法编组参数#1":无效的托管/非托管类型组合(此值类型必须与Struct配对)."
"Cannot marshal 'parameter #1': Invalid managed/unmanaged type combination (this value type must be paired with Struct)."
尽管我找到了在这种情况下使用LPStruct的MSDN文章.
Though I found an MSDN article that uses LPStruct in exactly this context.
这是我要封送的结构:
[StructLayout(LayoutKind.Sequential)]
public struct UserRec {
[MarshalAs(UnmanagedType.I4)]
public int userParam1;
}
这是C ++函数:
MOCKVADAVLIB_API tVDACQ_CallBackRec * TheFunction(void * userParams) {...
推荐答案
尝试将结构作为ref参数传递.
Try passing the structure as a ref parameter.
[DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr TheFunction(ref UserRec userRec);
当您将ref与结构结合使用时,它在概念上会传递地址.
When you use a ref combined with a structure, it conceptually passes the address.
这篇关于如何将结构封送为指向结构的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!