DllImport and char*

孤街醉人 提交于 2019-11-28 04:06:40

问题


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.


回答1:


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);
  }
}



回答2:


The StringBuilder is probably the way to go, but you have to set the capacity of the string builder before calling the function. Since C# has no idea how much memory that GetDriveLeter will use, you must make sure the StringBuilder has enough space. The marshaller will then pass a char* allocated to that length to the function and marhsall it back to the StringBuilder.

[return:MarshalAsAttribute(UnmanagedType.I4)]
private static extern bool GetDriveLetter(StringBuilder DriveLetter);

public static bool GetDriveLetter(out string driverLetter) {
  StringBuilder buffer = new StringBuilder(10);
  bool ret = GetDriveLetter(buffer);
  driveLetter = buffer.ToString();
  return ret;
}

See the p/invoke sample for GetWindowText(), for an example.




回答3:


[DllImport("mydll.dll")]
public static extern bool GetDriveLetter([MarshalAs(UnmanagedType.LPStr)]  string DriveLetter)


来源:https://stackoverflow.com/questions/2568436/dllimport-and-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!