Supplied buffer size is incorrect C#?

CakeDev 70 Reputation points
2024-08-04T22:59:48.7866667+00:00

Alright, hopefully this is my last question on this topic. Currently, I'm having trouble with a program that reads HID input from Joy-Cons to see their button input. When I try to run my program, I get the error code 1784 from ReadFile for a invalid user buffer. But, I'm fairly certain my buffer SHOULD be good. It's 49 bytes the correct size for a input report for a default nintendo Joy-Con (I'm fairly certain of this fact). Here's a snippet of my code if you would like to take a look.

IntPtr pDevicePathName = new IntPtr(detailDataBuffer.ToInt64() + Marshal.OffsetOf<SP_DEVICE_INTERFACE_DETAIL_DATA>("DevicePath").ToInt64());

string devicePath = Marshal.PtrToStringAuto(pDevicePathName);

string searchString1 = "pid&2007";

string searchString2 = "pid&2006";

string VIDstring = "vid&0002057e";

if (devicePath != null && (devicePath.Contains(searchString1) || devicePath.Contains(searchString2)) && devicePath.Contains(VIDstring))

{

Console.WriteLine("Device found!");

IntPtr hHid = CreateFile(devicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);

if (hHid != INVALID_HANDLE_VALUE)

{

Console.WriteLine("Works.");

byte[] buffer = new byte[49];

uint bytesRead;

OVERLAPPED overlapped = new OVERLAPPED();

overlapped.Offset = 0;

overlapped.OffsetHigh = 0;

overlapped.hEvent = IntPtr.Zero;

if (!ReadFile(hHid, buffer, (uint)buffer.Length, out bytesRead, ref overlapped))

{

int errorCode = Marshal.GetLastWin32Error();

Console.WriteLine("Error Message: " + new System.ComponentModel.Win32Exception(errorCode).Message);

}

else

{

Console.WriteLine("Read successful. Bytes read: " + bytesRead);

}

CloseHandle(hHid);

}

else

{

int errorCode = Marshal.GetLastWin32Error();

Console.WriteLine("CreateFile failed. Error Message: " + new System.ComponentModel.Win32Exception(errorCode).Message);

}

}

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,653 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,012 questions
{count} votes

1 answer

Sort by: Most helpful
  1. CakeDev 70 Reputation points
    2024-08-05T19:17:15.7866667+00:00

    I believe I fixed the problem! The problem was that I was stupid and just didn't know the correct byte size for the input buffer. I used HidP_GetCaps in C++ to get the input buffer size in bytes and it turns out its actually 362 bytes.

    2 people found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.