MATLAB: Do I receive an “??? A structure is required.” error when working with LIBPOINTER or CALLLIB in MATLAB 7.12 (R2011a) and a function which has an HWND input parameter

MATLAB

I want to use LOADLIBRARY/CALLLIB to call a library which uses the HWND datatype (from windows.h). In MATLAB versions prior to MATLAB 7.12 (R2011a) this datatype would be interpreted as a voidPtr:
>> loadlibrary('libmy','libmy.h');
>> libfunctions('libmy','-full')
Functions in library libmy:
voidPtr myFun(voidPtr)
In MATLAB 7.12 (R2011a) and newer it is interpreted as HWND__Ptr however:
>> loadlibrary('libmy','libmy.h');
>> libfunctions('libmy','-full')
Functions in library libmy:
HWND__Ptr myFun(HWND__Ptr)
This means that I can no longer do things like:
>> h = calllib('libmy','myFun',0)
??? Error using ==> calllib
A structure is required.
Or:
>> libpointer('uint32Ptr',0);
>> calllib('libmy','myFun',h)
??? Error using ==> calllib
A structure is required.
I also tried the following:
>> libpointer('HWND__Ptr',0);
But that also threw an error:
>> libpointer('HWND__Ptr',0);
??? A structure is required.
Error in ==> libpointer at 18
ptr=lib.pointer(varargin{:});

Best Answer

Please note that your original MATLAB code may actually not have been correct because when working with functions which expect an HWND input there are basically two situations (please check the documentation of your library):
1. You actually want to pass a NULL pointer. Some functions offer some extra functionality (like callbacks) if you have a Window and you pass a handle to this Window to the function. If you pass a NULL pointer however, that is also fine, the extra functionality will just not be used. In that case you can pass a NULL pointer from MATLAB using the LIBPOINTER function without input arguments:
>> calllib('libmy','myFun',libpointer);
2. You need to pass an actual HWND handle to a Window. In that case you would usually obtain this handle by calling functions like GetForegroundWindow or FindWindow from the Windows API; for example:
>> h = calllib('user32','GetForegroundWindow');
And then you can pass this variable h to the function:
>> h = calllib('user32','GetForegroundWindow');
>> [status,h,text] = calllib('user32','GetWindowTextA',h,uint8(blanks(128)),128);
>> text = char(text)
text =
MATLAB 7.12.0 (R2011a)
If you do really need the behavior of the previous MATLAB versions you can:
1. Use the 'mfilename' of LOADLIBRARY to first generate a prototype file for the library, then in this prototype file replace all instances of HWND__Ptr with voidPtr. And from then on use LOADLIBRARY with this prototype file instead of with the original header. Or,
2. Create a modified header in which you replace all instances of "HWND" with "void*".