我正在尝试将以下方法从 C++ 转换为 C#
HRESULT GetDevices(
[in, out] LPWSTR *pPnPDeviceIDs,
[in, out] DWORD *pcPnPDeviceIDs
);
在 MSDN 文档中它说:
pPnPDeviceIDs [in, out]
调用者分配的字符串指针数组,保存所有连接设备的即插即用名称。要了解此参数所需的大小,请首先将此参数设置为NULL
和调用此方法pcPnPDeviceIDs
设置为零,然后根据检索到的值分配缓冲区pcPnPDeviceIDs
。
pPnPDeviceIDs
pcPnPDeviceIDs [in, out] 在输入时,可以保存的值的数量。输出时,指向实际写入的设备数量的指针pPnPDeviceIDs
。
到目前为止,我有这个定义:
[PreserveSig]
int GetDevices(
[In, Out] IntPtr pPnPDeviceIDs,
[In, Out] ref uint pcPnPDeviceIDs
);
我试过用Marshal.AllocCoTaskMem
for分配一些内存pPnPDeviceIDs
分配一些内存,但是当我尝试调用该方法时出现 AccessViolationException。
谁能告诉我正确的转换方法LPWSTR *
当它是一个字符串指针数组时,
编辑:这是我的定义:
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("a1567595-4c2f-4574-a6fa-ecef917b9a40")]
public interface IPortableDeviceManager
{
[PreserveSig]
HRESULT GetDeviceDescription(
[In] string pszPnpDeviceID,
[In, Out] ref StringBuilder pDeviceDescription,
[In, Out] ref uint pcchDeviceDescription);
[PreserveSig]
HRESULT GetDeviceFriendlyName(
[In] string pszPnPDeviceID,
[In, Out] ref StringBuilder pDeviceFriendlyName,
[In, Out] ref uint pcchDeviceFriendlyName);
[PreserveSig]
HRESULT GetDeviceManufacturer(
[In] string pszPnPDeviceID,
[In, Out] ref StringBuilder pDeviceManufacturer,
[In, Out] ref uint pcchDeviceManufacturer);
[PreserveSig]
HRESULT GetDeviceProperty(
[In] string pszPnPDeviceID,
[In] string pszDevicePropertyName,
[In, Out] IntPtr pData,
[In, Out] ref uint pcbData,
[In, Out] ref uint pdwType);
[PreserveSig]
HRESULT GetDevices(
[In, Out] IntPtr pPnPDeviceIDs,
[In, Out] ref uint pcPnPDeviceIDs);
[PreserveSig]
HRESULT GetPrivateDevices(
[In, Out] IntPtr pPnPDeviceIDs,
[In, Out] ref uint pcPnPDeviceIDs);
[PreserveSig]
HRESULT RefreshDeviceList();
}
/// <summary>
/// CLSID_PortableDeviceManager
/// </summary>
[ComImport, Guid("0af10cec-2ecd-4b92-9581-34f6ae0637f3")]
public class CLSID_PortableDeviceManager { }
这是我的测试代码:
var devManager = Activator.CreateInstance(
typeof(CLSID_PortableDeviceManager)) as IPortableDeviceManager;
uint pcPnPDeviceIDs = 0;
var res1 = devManager.GetDevices(IntPtr.Zero, ref pcPnPDeviceIDs);
// check for errors in res1
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Marshal.AllocCoTaskMem((int)(IntPtr.Size * pcPnPDeviceIDs));
var res2 = devManager.GetDevices(ptr, ref pcPnPDeviceIDs);
// check for errors in res2
IntPtr ptr2 = ptr;
for (uint i = 0; i < pcPnPDeviceIDs; i++)
{
string str = Marshal.PtrToStringUni(ptr2);
ptr2 += IntPtr.Size;
}
}
finally
{
if (ptr != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(ptr);
}
}
Marshal.ReleaseComObject(devManager);
我在第二次调用 GetDevices() 时收到 AccessViolationException