DllImport and char*

前端 未结 4 2154
我在风中等你
我在风中等你 2020-12-19 05:33

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



        
4条回答
  •  独厮守ぢ
    2020-12-19 05:45

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

提交回复
热议问题