首页 / C# / 使用C#中的数组成员的Marshal结构
使用C#中的数组成员的Marshal结构
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用C#中的数组成员的Marshal结构,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2081字,纯文字阅读大概需要3分钟。
内容图文
![使用C#中的数组成员的Marshal结构](/upload/InfoBanner/zyjiaocheng/807/9ddbfcc1261f442ebe400b635aa69609.jpg)
我正在使用带有P / Invoke的C#来访问DLL方法.该方法的定义如下:
[DllImport("userManager.dll")]
static extern int GetUsers(out IntPtr userList);
原始结构:
typedef struct user_list {
unsigned short NumUsers;
USER_LIST_ITEM List[VARLEN];
} USER_LIST
typedef struct user_list_item {
char name[260];
unsigned char address[256];
} USER_LIST_ITEM
我完成的结构布局如下:
[StructLayout(LayoutKind.Sequential)]
public class USER_LIST
{
public uint NumUsers;
[MarshalAs(UnmanagedType.ByValArray)]
public USER_LIST_ITEM [] List;
}
[StructLayout(LayoutKind.Sequential)]
public class USER_LIST_ITEM
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string address;
};
但是当我尝试解组它时,我收到一个错误:
USER_LIST userList = new USER_LIST();
// Prepare pointer
IntPtr uList = Marshal.AllocHGlobal(Marshal.SizeOf(userList));
Marshal.StructureToPtr(userList, uList, false);
result = GetUsers(out uList);
Marshal.PtrToStructure(uList, userList); <--
The runtime has encountered a fatal error. The address of the error was at 0x79f82af6, on thread 0x464. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
我正确地获得了NumUsers属性,但是当解组数组时似乎发生了错误.有什么想法吗?
解决方法:
如果在用作out参数的结构中指定数组,则需要告诉编组器数组的长度.使用您的代码,封送程序可能正在分配一个零长度数组或只使用null,这会产生崩溃.遗憾的是,似乎无法将变长的out数组指定为结构的成员,因为MarshalAs.SizeParamIndex仅适用于方法.您可能会使用MarshalAs.SizeConst指定一个大型的恒定大小数组,但通常您必须解析(可能是被调用者分配的)返回缓冲区,如下所示:
var count = Marshal.ReadInt32 (uList) ;
var users = new List<USER_LIST_ITEM> () ;
var ptr = (long)uList + 4 ;
for (int i = 0 ; i < count ; ++i)
{
users.Add (Marshal.PtrToStructure (typeof (USER_LIST_ITEM),
new IntPtr (ptr))) ;
ptr += Marshal.SizeOf (typeof (USER_LIST_ITEM)) ;
}
你必须特别注意对齐和填充以及32/64位问题.
内容总结
以上是互联网集市为您收集整理的使用C#中的数组成员的Marshal结构全部内容,希望文章能够帮你解决使用C#中的数组成员的Marshal结构所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。