Why does my C#/pinvoke DeviceIoControl call return 0 bytes read with garbage data?

China☆狼群 提交于 2019-12-10 10:04:00

问题


I have an unmanaged C++ Windows console app that works fine. I want it in C#. I have done DllImport statements for the necessary Kernel32.dll symbols:

[StructLayout(LayoutKind.Sequential)]
internal struct DiskGeometry
{
    public long Cylinders;
    public int MediaType;
    public int TracksPerCylinder;
    public int SectorsPerTrack;
    public int BytesPerSector;
}

internal static class NativeMethods
{
    internal const uint FileAccessGenericRead = 0x80000000;
    internal const uint FileShareWrite = 0x2;
    internal const uint FileShareRead = 0x1;
    internal const uint CreationDispositionOpenExisting = 0x3;
    internal const uint IoCtlDiskGetDriveGeometry = 0x70000;

    [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern SafeFileHandle CreateFile(
        string fileName,
        uint fileAccess,
        uint fileShare,
        IntPtr securityAttributes,
        uint creationDisposition,
        uint flags,
        IntPtr template);

    [DllImport("Kernel32.dll", SetLastError = false, CharSet = CharSet.Auto)]
    public static extern int DeviceIoControl(
        SafeFileHandle device,
        uint controlCode,
        IntPtr inBuffer,
        uint inBufferSize,
        IntPtr outBuffer,
        uint outBufferSize,
        ref uint bytesReturned,
        IntPtr overlapped);
}

I then have the following application code:

    public static void Main()
    {
        SafeFileHandle diskHandle = NativeMethods.CreateFile(
            "\\\\.\\PhysicalDrive0",
            NativeMethods.FileAccessGenericRead,
            NativeMethods.FileShareWrite | NativeMethods.FileShareRead,
            IntPtr.Zero,
            NativeMethods.CreationDispositionOpenExisting,
            0,
            IntPtr.Zero);
        if (diskHandle.IsInvalid)
        {
            Console.WriteLine("CreateFile failed with error: {0}", Marshal.GetLastWin32Error());
            return;
        }

        int geometrySize = Marshal.SizeOf(typeof(DiskGeometry));
        Console.WriteLine("geometry size = {0}", geometrySize);

        IntPtr geometryBlob = Marshal.AllocHGlobal(geometrySize);

        uint numBytesRead = 0;
        if (0 == NativeMethods.DeviceIoControl(
            diskHandle,
            NativeMethods.IoCtlDiskGetDriveGeometry,
            IntPtr.Zero,
            0,
            geometryBlob,
            (uint)geometrySize,
            ref numBytesRead,
            IntPtr.Zero))
        {
            Console.WriteLine("DeviceIoControl failed with error: {0}", Marshal.GetLastWin32Error());
            return;
        }

        Console.WriteLine("Bytes read = {0}", numBytesRead);

        DiskGeometry geometry = (DiskGeometry)Marshal.PtrToStructure(geometryBlob, typeof(DiskGeometry));
        Marshal.FreeHGlobal(geometryBlob);

        long bytesPerCylinder = (long)geometry.TracksPerCylinder * (long)geometry.SectorsPerTrack * (long)geometry.BytesPerSector;
        long totalSize = geometry.Cylinders * bytesPerCylinder;

        Console.WriteLine("Media Type:           {0}", geometry.MediaType);
        Console.WriteLine("Cylinders:            {0}", geometry.Cylinders);
        Console.WriteLine("Tracks per Cylinder:  {0}", geometry.TracksPerCylinder);
        Console.WriteLine("Sectors per Track:    {0}", geometry.SectorsPerTrack);
        Console.WriteLine("Bytes per Sector:     {0}", geometry.BytesPerSector);
        Console.WriteLine("Bytes per Cylinder:   {0}", bytesPerCylinder);
        Console.WriteLine("Total disk space:     {0}", totalSize);
    }

My C# app prints "Bytes read = 0" and the geometry member values are garbage. I am certainly no expert on DllImport and marshaling. Please help me understand what I am doing wrong. If I change the fifth parameter to DeviceIoControl to be "ref DiskGeometry" and just pass in one created right before the call (instead of IntPtr and alloc), all printed geometry member values are 0.


回答1:


You have mistype, try this:

internal const uint IoCtlDiskGetDriveGeometry = 0x70000;



回答2:


Try using one of those signatures for the DllImport: http://pinvoke.net/default.aspx/kernel32.DeviceIoControl



来源:https://stackoverflow.com/questions/13712212/why-does-my-c-pinvoke-deviceiocontrol-call-return-0-bytes-read-with-garbage-dat

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