Skip to content

Instantly share code, notes, and snippets.

@jonforums
Created March 16, 2011 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonforums/872458 to your computer and use it in GitHub Desktop.
Save jonforums/872458 to your computer and use it in GitHub Desktop.
Ruby 1.9.2 DL nested structs
require 'dl/import'
require 'dl/types'
module Win32FileAPI
extend DL::Importer
dlload 'kernel32.dll', 'user32.dll'
include DL::Win32Types
# structs
SECURITY_ATTRIBUTES = struct [
'DWORD nLength',
'PVOID lpSecurityDescriptor',
'BOOL bInheritHandle',
]
typealias 'PSECURITY_ATTRIBUTES', 'SECURITY_ATTRIBUTES*'
# FIXME these 3 are wrong
OL_OFFSET = struct [
'DWORD Offset',
'DWORD OffsetHigh',
]
OL_UNION = union [
'OL_OFFSET _offset',
'PVOID Pointer',
]
OVERLAPPED = struct [
'PDWORD Internal',
'PDWORD InternalHigh',
'OL_UNION _internal',
'HANDLE hEvent',
]
typealias 'POVERLAPPED', 'OVERLAPPED*'
# user32.dll functions
extern 'int MessageBoxA(HWND, LPCSTR, LPCSTR, UINT)', :stdcall
# kernel32.dll functions
extern 'HANDLE CreateFileA(LPCSTR, DWORD, DWORD, PSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE)', :stdcall
# XXX cheat? - BOOL ReadFile(HANDLE, PVOID, DWORD, PDWORD, char*)
# really cheat? - BOOL ReadFile(HANDLE, PVOID, DWORD, PDWORD, PVOID)
extern 'BOOL ReadFile(HANDLE, PVOID, DWORD, PDWORD, POVERLAPPED)', :stdcall
end
rv = Win32FileAPI::MessageBoxA(DL::NULL, 'Hello from Ruby 1.9 DL!', 'DL Info', 0x40 | 0x3)
puts rv
@dmajkic
Copy link

dmajkic commented Mar 27, 2011

Union means that members are overlaped - you can use either DWORDs Offset and OffsetHigh, or Pointer.

And MSDN states that Pointer should not be used, so I think you should try to directly delare Offset and OffsetHigh like


  OVERLAPPED = struct [
    'PDWORD Internal',
    'PDWORD InternalHigh',
    'DWORD Offset',
    'DWORD OffsetHigh',
    #'OL_UNION _internal', # skip since Offsets are declared directly
    'HANDLE hEvent',
  ]

And then OL_OFFSET and OL_UNION are not needed.

@jonforums
Copy link
Author

re: unions, understood. I overlooked Pointer's doc "Reserved for system use; do not use after initialization to zero."

I think you're right that it all collapses down to your struct example...thanks...back to looking at porting something like http://msdn.microsoft.com/en-us/library/aa365592(v=vs.85).aspx to ruby.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment