SwiftlyTilting: usability, reusability

Thursday, May 13, 2010

cStruct and WinAPI: Classes for accessing the Windows API with PHP and WinBinder

One of the biggest roadblocks to writing code which accesses the Windows API is the fact that so many functions require you to provide data formatted in specific format. This format is defined on MSDN as a C struct, which has no direct representation in PHP. The best you can hope for is to figure out the layout of the structure, and then set up some PACK/UNPACK calls to convert the data to and from something more useful in PHP.

Enter cStruct, a collection of objects that helps provide support for C-like structures. All common data types have been implemented. This will save lots of time as you don’t have to remember or figure out how many bytes each datatype takes up and how to convert it to and from binary data.

Download cStruct.0.2.2
Downloaded 2071 times

Using cStruct


Here is the type definition from MSDN:

typedef struct _DISPLAY_DEVICE {
  DWORD cb;
  TCHAR DeviceName[32];
  TCHAR DeviceString[128];
  DWORD StateFlags;
  TCHAR DeviceID[128];
  TCHAR DeviceKey[128];

and the equivalent PHP using cStruct:

class DISPLAY_DEVICE extends cStruct
{   static protected $typedef = "
      DWORD cb;
      TCHAR DeviceName[32];
      TCHAR DeviceString[128];
      DWORD StateFlags;
      TCHAR DeviceID[128];
      TCHAR DeviceKey[128];

Then using it is very easy:

$displayDev = new DISPLAY_DEVICE();

// cb needs to contain the size of the structure before calling EnumDisplayDevices
$displayDev->cb = DISPLAY_DEVICE::sizeOf();  

// call WinAPI function
User32::EnumDisplayDevices(null, 0, $displayDev , 0);

wb_message_box(null, "Using Display: " . $displayDev->DeviceString);

Using WinAPI

Using WinAPI to call Windows functions is simple. If the function is contained in Kernel32, User32, Gdi32 or Comctl32, just use the following syntax:

// LibraryName::Function($param1, $param2, ..., $paramN);
// Example:
User32::EnumDisplayDevices(null, 0, $tempData , 0);

To access other libraries, use this code:

//WinAPI::LibraryName()->Function($param1, $param2, ..., $paramN);
// This is perfectly valid, but is more meant for other DLLs, not built in windows functions)
WinAPI::User32()->EnumDisplayDevices(null, 0, $tempData , 0);

See the wiki page with documentation here: coming soon
See the doxygen generated help here: Code Documentation

Download cStruct.0.2.2
Downloaded 2071 times

Package Includes:
- Latest WinAPI.php
- Example script

Note: cStruct and WinAPI require PHP 5.3+ with the Winbinder extension

1 Comment Leave Comment

Wow! Finally I got a website from where I can in fact obtain helpful information concerning my study
and knowledge.

Comment by Damian — Thursday, June 18, 2015 @ 12:08 pm

Leave a Comment

Validate XHTML | Word Press