Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

BOOL GetDriveLetter(OUT char* DriveLetter)

I've tried

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

and

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

but neither returned anything in the DriveLetter variable.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
531 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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 = GetDriveLetter(ptr);
    if ( ret ) {
      drive = Marshal.PtrToStringAnsi(ptr);
    }
    return ret;
  } finally { 
    Marshal.FreeHGlobal(ptr);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...