I have a C# application, compiled in Visual Studio 2017 on the 'Any CPU' target, with the 'Prefer 32-bit' option disabled. In this application, I am trying to pinvoke kernel32!GetBinaryType(). When running with 'Prefer 32-bit' enabled, it works fine. When running in either 32 or 64-bit mode from a C++ executable, it works fine. I am not sure what I am doing wrong with the 64-bit C# application.
This is my pinvoke signature:
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetBinaryTypeW([MarshalAs(UnmanagedType.LPWStr)] string path, out UInt32 result);
Calling this from 64 bit mode, GetLastError()
returns 193, which according to https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx is
ERROR_BAD_EXE_FORMAT.
I have attached a 64-bit debugger to both my C# application and my C++ application to make sure that the string is reaching GetBinaryTypeW()
in the correct place on the stack, and it appears to me that it is.
I am concerned that I have run into some subtle bug in the marshaler.
What is wrong with my approach?
Update
The question referenced in the comments does not match this situation. In that question, a call to LoadLibrary()
failed because it was being used to try and load a 32 bit DLL into a 64 bit process. I am not trying to load any DLL. I am merely trying to use GetBinaryType() to examine the PE header of an executable.