1

我有以下 C++ 方法的签名。最后一个参数应将设备名称作为 2 字节的 unicode 字符串返回。

int GetDeviceIdentifier(DWORD deviceIndex, WCHAR** ppDeviceName);

我使用以下签名包装到 C# 中。它有效,但我得到的字符串很奇怪。难道我做错了什么?

[DllImportAttribute("StclDevices.dll", EntryPoint = "GetDeviceIdentifier", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern int GetDeviceIdentifier(uint deviceIndex, StringBuilder ppDeviceName);
4

2 回答 2

3

传递StringBuilder参数将匹配类型为 的 C++ 参数WCHAR*。在这种情况下,内存将由 C# 代码通过设置字符串构建器对象的容量来分配。

对于您的函数,看起来内存是由 C++ 代码分配的。因此双指针。所以你需要这个:

[DllImportAttribute("StclDevices.dll", 
    CallingConvention=CallingConvention.Cdecl)]
public static extern int GetDeviceIdentifier(
    uint deviceIndex, 
    out IntPtr ppDeviceName
);

你这样称呼它:

IntPtr ppDeviceName;
int retval = GetDeviceIdentifier(deviceIndex, out ppDeviceName);
string DeviceName = Marshal.PtrToStringUni(ppDeviceName);
于 2013-01-15T16:29:13.710 回答
0
[DllImportAttribute("StclDevices.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
internal static extern Int32 GetDeviceIdentifier([In] UInt32 deviceIndex, [MarshalAs(UnmanagedType.LPTStr), Out] out String ppDeviceName);

String ppDeviceName;
NativeMethods.GetDeviceIdentifier(i, out ppDeviceName);

如果您想坚持使用 StringBuilder,请改用:

[DllImportAttribute("StclDevices.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
internal static extern Int32 GetDeviceIdentifier([In] UInt32 deviceIndex, [In, Out] StringBuilder ppDeviceName);

StringBuilder ppDeviceName = new StringBuilder(255);
NativeMethods.GetDeviceIdentifier(i, ppDeviceName);
于 2013-01-15T16:32:18.170 回答