c# - 在 C# 中调用 C++ dll 方法
问题描述
我正在尝试在 C# 中调用 C++ DLL 方法,我之前已经成功调用了一些方法,但下面的方法总是失败,我对此一无所知:
C ++ 手册文档中的此描述:
方法头:
BOOL SxuptpEnumDevices (
DWORD dwIpaddr, /* Device server IP address*/
LPVOID lpbDevices, /* Array address of the structure */
DWORD cbBuf, /* Number of bytes of array */
LPDWORD lpdwReaded, /* Parameter address to which the number of byte copied will be returned */
LPDWORD lpdwReturned /* Parameter address to which the number of structure copied will be returned */ );
方法说明:
dwIpaddr:指定将列出 USB 设备的设备服务器的 IP 地址。
lpbDevices : 指示 SXUSBDEVICE 结构数组的指针。它接收 USB 设备列表。
cbBuf:按字节指定 lpbDevices 指向的数组的大小。
lpdwReaded:表示复制到 lpbDevices 的字节数。
lpdwReturned:指示返回列出的 USB 设备数量的参数的指针。
*返回值:函数成功完成时返回TRUE,否则返回FALSE。
笔记:
typedef struct _SXUSBDEVICE {
char szPortName[32]; /* USB logical port name */
char szDeviceName[64]; /* Device Name */
DWORD dwIpPc; /* IP address of connected PC */
WORD wStatus; /* Status information */
WORD wVid; /* Device VID */
WORD wPid; /* Device PID */
char szLocation[16]; /* USB port info which the device is connected to */
WORD wClass; /* USB Interface Class */
} SXUSBDEVICE, *LPSXUSBDEVICE;
在 C++ 中调用:
BOOL result = SxuptpEnumDeviceServers(NULL, 0, &lpbDevices, (sizeof(SXPSERVER) * MAX_PSERVER), &dwReaded, &dwReturned);
if(result){
//dwReturned = 1
//lpbDevices[dwReturned - 1] will have value
}
C#
方法头
[DllImport(@"Sxuptp.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "SxuptpEnumDevices")]
public static extern bool SxuptpEnumDevices(
uint dwIpaddr,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] SXPSERVER[] lpbDevices,
uint cbBuf,
ref uint lpdwReaded,
ref uint lpdwReturned);
笔记:
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct SXUSBDEVICE
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public char[] szPortName; // USB logical port name
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
public char[] szDeviceName; // Device Name
public uint dwIpPc; // IP address of connected PC
public ushort wStatus; // Status information
public ushort wVid; // Device VID
public ushort wPid; // Device PID
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] szLocation; // USB port info which the device is connected to
public ushort wClass; // USB Interface Class
}
在我的项目中使用方法:
//Get all devices in USB Device Server from IP
int MAX_DEVICES = 64;
uint dwIpaddr = (uint)IPAddress.NetworkToHostOrder((int)IPAddress.Parse("169.254.95.193").Address);
SXUSBDEVICE[] lpbDevices = new SXUSBDEVICE[MAX_DEVICES];
uint lpdwReaded = 0,
lpdwReturned = 0,
cbuf = (uint)(Marshal.SizeOf(typeof(SXUSBDEVICE)) * MAX_DEVICES);
if (Driver.Sxuptp.SxuptpEnumDevices(dwIpaddr, lpbDevices, cbuf, ref lpdwReaded, ref lpdwReturned))
{
MessageBox.Show($"lpdwReaded: {lpdwReaded}, lpdwReturned: {lpdwReturned}");
}
else
{
MessageBox.Show("Error");
}
这种方法总是返回 false,我认为某些 C# 代码在某处有一些错误,但我对此一无所知。请教我或提醒我任何东西来解决它!