问题描述
我有一个试图通过PInvoke从C#应用程序使用的第三方非托管dll。非托管代码的相关部分如下:
unsigned char WINAPI GetDeviceInfo(PDEVICES pDevInfo,unsigned int *retError = NULL);
typedef struct _tag_DEVICE_INFO{
unsigned int dev_Index;
wchar_t dev_MakerName[256]; // Maker Name
unsigned int dev_MakerName_Length;
wchar_t dev_ModelName[256]; // Model Name
unsigned int dev_ModelName_Length;
}DEVICE_INFO,*PDEVICE_INFO;
typedef struct _tag_DEVICES{
unsigned int Device_Count; // Number of devices detected
wchar_t *Device_IDs[512];
DEVICE_INFO Device_Info[512]; // Detected device information: Maximum 256
}DEVICES,*PDEVICES;
我的C#代码是这样:
using System;
using System.Runtime.InteropServices;
namespace scratch
{
class Program
{
[DllImport("Lmxptpif.dll",SetLastError = true)]
public static extern byte GetDeviceInfo([In,Out,MarshalAs(UnmanagedType.LPStruct)] DEVICES pDevInfo,out uint retError);
[StructLayout(LayoutKind.Sequential,CharSet = CharSet.Auto)]
public struct DEVICE_INFO
{
public uint dev_Index;
public string dev_MakerName; // Maker Name
public uint dev_MakerName_Length;
public string dev_ModelName; // Model Name
public uint dev_ModelName_Length;
}
[StructLayout(LayoutKind.Sequential,CharSet = CharSet.Auto)]
public struct DEVICES
{
[MarshalAs(UnmanagedType.U4)]
public uint Device_Count; // Number of devices detected
[MarshalAs(UnmanagedType.ByValArray,SizeConst=512,ArraySubType=UnmanagedType.LPWStr)]
public string[] Device_IDs; // Array of Device IDs (512 PWSTRs)
public DEVICE_INFO[] Device_Info;
}
static void Main(string[] args)
{
uint retError = 0;
DEVICES pInfo = new DEVICES();
byte result = GetDeviceInfo(pInfo,out retError);
if (result == 1 && retError == 0)
{
string models = "";
for (int i = 0; i < pInfo.Device_Count; i++)
{
models += pInfo.ToString();
}
}
}
}
}
运行代码时,对GetDeviceInfo()的调用将引发异常:
System.Runtime.InteropServices.MarshallDirectiveException: '无法编组'参数#1':无效的托管/未托管类型 组合(此值类型必须与Struct配对)。'
我不明白该错误消息试图告诉我什么。
定义“结构”和肠功能声明的正确方法是什么?如何解决此问题,以便函数调用成功?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)