C# 调用C++dll的参数为数据结构指针的指针

EasonLouis EasonLouis 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
C++的dll
HRESULT extern WINAPI WFSGetInfo ( HSERVICE hService, DWORD dwCategory, LPVOID lpQueryDetails, DWORD dwTimeOut, LPWFSRESULT * lppResult);

结构体
typedef struct _wfs_result
{
REQUESTID RequestID;
HSERVICE hService;
SYSTEMTIME tsTimestamp;
HRESULT hResult;
union {
DWORD dwCommandCode;
DWORD dwEventID;
} u;
LPVOID lpBuffer;
} WFSRESULT, * LPWFSRESULT;
typedef struct _wfs_idc_status
{
WORD fwDevice;
WORD fwMedia;
WORD fwRetainBin;
WORD fwSecurity;
USHORT usCards;
WORD fwChipPower;
LPSTR lpszExtra;
} WFSIDCSTATUS, *LPWFSIDCSTATUS;


c#的定义
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct WFSRESULT1
{
public UInt32 RequestID;
public ushort hService;
public _SYSTEMTIME tsTimestamp;//对应下面的 _SYSTEMTIME
public int hResult;
public AnonymousStruct U;//对应下面的 AnonymousStruct 结构
public IntPtr lpBuffer;//返回的指针,指向_wfs_idc_status 这个结构
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct LPStruct
{
public IntPtr ptrWFSRESULT;//返回的指针,指向WFSRESULT1 这个结构
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _wfs_idc_status
{
public UInt16 fwDevice;
public UInt16 fwMedia;
public UInt16 fwRetainBin;
public UInt16 fwSecurity;
public ushort usCards;
public UInt16 fwChipPower;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 999)]
public string lpszExtra;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _SYSTEMTIME
{
public UInt16 wYear;
public UInt16 wMonth;
public UInt16 wDayOfWeek;
public UInt16 wDay;
public UInt16 wHour;
public UInt16 wMinute;
public UInt16 wSecond;
public UInt16 wMilliseconds;
}
[DllImport("msxfs.dll", CharSet = CharSet.Ansi)]
public static extern int WFSGetInfo(int iService, int iCategory, string sQueryDetail, int iTimeOut, ref IntPtr ptr);


C#执行
            LPStruct lpStruct = new LPStruct();
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(lpStruct));
Marshal.StructureToPtr(lpStruct, ptr, false);
int iRet = WFSGetInfo(m_service, WFS_INF_IDC_STATUS, null, 2000, ref ptr);
lpStruct = (LPStruct)Marshal.PtrToStructure(ptr, typeof(LPStruct));
WFSRESULT1 wfsR1;
wfsR1 = (WFSRESULT1)Marshal.PtrToStructure(lpStruct.ptrWFSRESULT, typeof(WFSRESULT1));//运行会在Application.Run()里面报错"未处理AccessViolationException。尝试读取或写入受保护的内存。这通常指示其他内存已损坏。"
_wfs_idc_status stat1 = (_wfs_idc_status)Marshal.PtrToStructure(wfsR1.lpBuffer, typeof(_wfs_idc_status));


请求各位高手指教,是我定义和操作结构体错误导致的吗?
...全文
评论 4
收藏 已收藏
分享
返回顶部
EasonLouis
C# 111,129 成员 642,540 内容