的DllImport与char *DllImport、char

2023-09-03 05:22:11 作者:失去一个又一个

我有一个方法,我想从一个DLL导入和它的签名:

I have a method I want to import from a DLL and it has a signature of:

BOOL GetDriveLetter(OUT char* DriveLetter)

我试过

    [DllImport("mydll.dll")]
    public static extern bool GetDriveLetter(byte[] DriveLetter);

    [DllImport("mydll.dll")]
    public static extern bool GetDriveLetter(StringBuilder DriveLetter);

但无论返回的驱动器号变任何东西。

but neither returned anything in the DriveLetter variable.

推荐答案

它看起来像函数 GetDriveLetter 期待一个的char * 指向足够的内存来容纳的驱动器盘符。

It looks like the function GetDriveLetter is expecting a char* which points to sufficient memory to contain the drive letter.

我觉得要解决这个问题最简单的方法是通过一个原始的的IntPtr ,敷调用 GetDriveLetter 在API,它负责资源管理和转换到字符串

I think the easiest way to approach this problem is to pass a raw IntPtr and wrap the calls to GetDriveLetter in an API which takes care of the resource management and conversion to a string.

[return:MarshalAsAttribute(UnmanagedType.Bool)]
private static extern bool GetDriveLetter(IntPtr ptr);

public static bool GetDriveLetter(out string drive) {
  drive = null;
  var ptr = Marshal.AllocHGlobal(10);
  try {
    var ret = GetDriveLitter(ptr);
    if ( ret ) {
      drive = Marshal.PtrToStringAnsi(ptr);
    }
    return ret;
  } finally { 
    Marshal.FreeHGlobal(ptr);
  }
}