DllImport and char*

前端 未结 4 2165
我在风中等你
我在风中等你 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:39

    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.

提交回复
热议问题