C++ Retrieves HBITMAP, function passes to C#.DOTNET, Bitmap.FromHBitmap fails at runtime with "generic error in GDI+"

Andrew Painter 1 Reputation point
2021-01-04T18:28:49.167+00:00

I'm using a DLL written in C++ to make some WinAPI calls that retrieve an HBITMAP value. Then a C# Windows Forms program retrieves the HBITMAP via p/invoke, as IntPtr.

Both the DLL and the DotNET app referencing it are being built as x86 on a system running x64 Windows 10.

Debugging with breakpoints I can verify that the exact same pointer value is stored in the C++ fields and returned by the accessor function as is retrieved by the C# DotNET application.

Any attempt to get a DotNET Bitmap out of that IntPtr fails.

Using Bitmap.FromHBitmap( IntPtr ) throws the following exception:

An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll

Additional information: A generic error occurred in GDI+.

Trying to use an UnmanagedMemoryStream with Bitmap.FromStream() throws a different exception:

An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll

Additional information: Parameter is not valid.

Obviously there's a lot of interworking code and it's ridiculously dirty right now, with all my attempts to get the HBITMAP from C++/WinAPI Marshalled into C#/DotNET and working. A C++ Header and CPP file, a DotNET Windows Form file. I don't really want to have to remake multiple versions to post the real (readable) code that generates these errors. I will if nobody has a quick answer.

It may or may not be relevant that the C++ code uses a CLASS to perform GDI calls and store returned data, with extern "C" functions outside the class to retrieve class fields and return them to C# via p/invoke.

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.
10,458 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,584 questions
{count} votes