Class: Win32::API

Inherits:
Object
  • Object
show all
Defined in:
ext/win32/api.c

Direct Known Subclasses

Function

Defined Under Namespace

Classes: Callback, Error, Function, LoadLibraryError, PrototypeError

Constant Summary collapse

VERSION =

The version of the win32-api library

1.6.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#Win32::API.new(function, prototype = 'V') ⇒ Object

Creates and returns a new Win32::API object. The function is the name of the Windows function.

The prototype is the function prototype for function. This can be a string or an array of characters. The possible valid characters are ‘I’ (integer), ‘L’ (long), ‘V’ (void), ‘P’ (pointer), ‘K’ (callback) or ‘S’ (string).

The default is void (‘V’).

Constant (const char*) strings should use ‘S’. Pass by reference string buffers should use ‘P’. The former is faster, but cannot be modified.

The return argument is the return type for the function. The valid characters are the same as for the prototype. The default is ‘L’ (long).

The dll is the name of the DLL file that the function is exported from. The default is ‘kernel32’.

If the function cannot be found then an API::Error is raised (a subclass of RuntimeError).

Example:

require 'win32/api'
include Win32

buf = 0.chr * 260
len = [buf.length].pack('L')

GetUserName = API.new('GetUserName', 'PP', 'I', 'advapi32')
GetUserName.call(buf, len)

puts buf.strip


261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'ext/win32/api.c', line 261

static VALUE api_init(int argc, VALUE* argv, VALUE self)
{
   HMODULE hLibrary;
   FARPROC fProc;
   Win32API* ptr;
   int i;
   const char* first  = "A";
   const char* second = "W";
   VALUE v_proc, v_proto, v_return, v_dll;

   rb_scan_args(argc, argv, "13", &v_proc, &v_proto, &v_return, &v_dll);

   Data_Get_Struct(self, Win32API, ptr);

   // Convert a string prototype to an array of characters
   if(rb_respond_to(v_proto, rb_intern("split")))
      v_proto = rb_str_split(v_proto, "");

   // Convert a nil or empty prototype to 'V' (void) automatically
   if(NIL_P(v_proto) || RARRAY_LEN(v_proto) == 0){
      v_proto = rb_ary_new();
      rb_ary_push(v_proto, rb_str_new2("V"));
   }

   // Set an arbitrary limit of 20 parameters
   if(RARRAY_LEN(v_proto) > 20)
      rb_raise(rb_eArgError, "too many parameters: %ld", RARRAY_LEN(v_proto));

   // Set the default dll to 'kernel32'
   if(NIL_P(v_dll))
      v_dll = rb_str_new2("kernel32");

   // Set the default return type to 'L' (DWORD)
   if(NIL_P(v_return))
      v_return = rb_str_new2("L");

#if defined TAINTING_SUPPORT
   SafeStringValue(v_dll);
   SafeStringValue(v_proc);
#endif

   hLibrary = LoadLibrary(TEXT(RSTRING_PTR(v_dll)));

   // The most likely cause of failure is a bad DLL load path
   if(!hLibrary){
      rb_raise(cAPILoadError, "LoadLibrary() function failed for '%s': %s",
         RSTRING_PTR(v_dll),
         StringError(GetLastError())
      );
   }

   ptr->library = hLibrary;

   /* Attempt to get the function.  If it fails, try again with an 'A'
    * appended.  If that fails, try again with a 'W' appended. If that
    * still fails, raise an API::LoadLibraryError.
    */

   fProc = GetProcAddress(hLibrary, TEXT(RSTRING_PTR(v_proc)));

   // Skip the ANSI and Wide function checks for MSVCRT functions.
   if(!fProc){
      if(strstr(RSTRING_PTR(v_dll), "msvcr")){
         rb_raise(
            cAPILoadError,
            "Unable to load function '%s'",
            RSTRING_PTR(v_proc)
         );
      }
      else{
         VALUE v_ascii = rb_str_new3(v_proc);
         v_ascii = rb_str_cat(v_ascii, first, 1);
         fProc = GetProcAddress(hLibrary, TEXT(RSTRING_PTR(v_ascii)));

         if(!fProc){
            VALUE v_unicode = rb_str_new3(v_proc);
            v_unicode = rb_str_cat(v_unicode, second, 1);
            fProc = GetProcAddress(hLibrary, TEXT(RSTRING_PTR(v_unicode)));

            if(!fProc){
               rb_raise(
                  cAPILoadError,
                  "Unable to load function '%s', '%s', or '%s'",
                  RSTRING_PTR(v_proc),
                  RSTRING_PTR(v_ascii),
                  RSTRING_PTR(v_unicode)
               );
            }
            else{
               rb_iv_set(self, "@effective_function_name", v_unicode);
            }
         }
         else{
            rb_iv_set(self, "@effective_function_name", v_ascii);
         }
      }
   }
   else{
      rb_iv_set(self, "@effective_function_name", v_proc);
   }

   ptr->function = fProc;

   // Push the numeric prototypes onto our int array for later use.

   for(i = 0; i < RARRAY_LEN(v_proto); i++){
#if defined TAINTING_SUPPORT
      SafeStringValue(RARRAY_PTR(v_proto)[i]);
#endif
      switch(*(TCHAR*)StringValuePtr(RARRAY_PTR(v_proto)[i])){
         case 'L':
            ptr->prototype[i] = _T_LONG;
            break;
         case 'P':
            ptr->prototype[i] = _T_POINTER;
            break;
         case 'I': case 'B':
            ptr->prototype[i] = _T_INTEGER;
            break;
         case 'V':
            ptr->prototype[i] = _T_VOID;
            break;
         case 'K':
            ptr->prototype[i] = _T_CALLBACK;
            break;
         case 'S':
            ptr->prototype[i] = _T_STRING;
            break;
         default:
            rb_raise(cAPIProtoError, "Illegal prototype '%s'",
               StringValuePtr(RARRAY_PTR(v_proto)[i])
            );
      }
   }

   // Store the return type for later use.

   // Automatically convert empty strings or nil to type void.
   if(NIL_P(v_return) || RSTRING_LEN(v_return) == 0){
      v_return = rb_str_new2("V");
      ptr->return_type = _T_VOID;
   }
   else{
#if defined TAINTING_SUPPORT
      SafeStringValue(v_return);
#endif
      switch(*RSTRING_PTR(v_return)){
         case 'L':
            ptr->return_type = _T_LONG;
            break;
         case 'P':
            ptr->return_type = _T_POINTER;
            break;
         case 'I': case 'B':
            ptr->return_type = _T_INTEGER;
            break;
         case 'V':
            ptr->return_type = _T_VOID;
            break;
         case 'S':
            ptr->return_type = _T_STRING;
            break;
         default:
            rb_raise(cAPIProtoError, "Illegal return type '%s'",
               RSTRING_PTR(v_return)
            );
      }
   }

   rb_iv_set(self, "@dll_name", v_dll);
   rb_iv_set(self, "@function_name", v_proc);
   rb_iv_set(self, "@prototype", v_proto);
   rb_iv_set(self, "@return_type", v_return);

   return self;
}

Instance Attribute Details

#dll_nameObject (readonly)

The name of the DLL that exports the API function

#effective_function_nameObject (readonly)

The name of the actual function that is returned by the constructor. For example, if you passed ‘GetUserName’ to the constructor, then the effective function name would be either ‘GetUserNameA’ or ‘GetUserNameW’.

#function_nameObject (readonly)

The name of the function passed to the constructor

#prototypeObject (readonly)

The prototype, returned as an array of characters

#return_typeObject (readonly)

The return type, returned as a single character, S, P, L, I, V or B

Instance Method Details

#Win32::APIObject

Calls the function pointer with the given arguments (if any). Note that, while this method will catch some prototype mismatches (raising a TypeError in the process), it is not fulproof. It is ultimately your job to make sure the arguments match the prototype specified in the constructor.

For convenience, nil is converted to NULL, true is converted to TRUE (1) and false is converted to FALSE (0).



778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# File 'ext/win32/api.c', line 778

static VALUE api_call(int argc, VALUE* argv, VALUE self){
   VALUE v_proto, v_args, v_arg, v_return;
   Win32API* ptr;
   uintptr_t return_value;
   int i = 0;
   int len;

   struct{
      uintptr_t params[20];
   } param;

   Data_Get_Struct(self, Win32API, ptr);

   rb_scan_args(argc, argv, "0*", &v_args);

   v_proto = rb_iv_get(self, "@prototype");

   // For void prototypes, allow either no args or an explicit nil
   if(RARRAY_LEN(v_proto) != RARRAY_LEN(v_args)){
      char* c = StringValuePtr(RARRAY_PTR(v_proto)[0]);
      if(!strcmp(c, "V")){
         rb_ary_push(v_args, Qnil);
      }
      else{
         rb_raise(rb_eArgError,
            "wrong number of parameters: expected %ld, got %ld",
            RARRAY_LEN(v_proto), RARRAY_LEN(v_args)
         );
      }
   }

   len = RARRAY_LEN(v_proto);

   for(i = 0; i < len; i++){
      v_arg = RARRAY_PTR(v_args)[i];

      // Convert nil to NULL.  Otherwise convert as appropriate.
      if(NIL_P(v_arg))
         param.params[i] = (uintptr_t)NULL;
      else if(v_arg == Qtrue)
         param.params[i] = TRUE;
      else if(v_arg == Qfalse)
         param.params[i] = FALSE;
      else
         switch(ptr->prototype[i]){
            case _T_LONG:
               param.params[i] = NUM2SIZET(v_arg);
               break;
            case _T_INTEGER:
               param.params[i] = NUM2INT(v_arg);
               break;
            case _T_POINTER:
               if(FIXNUM_P(v_arg)){
                  param.params[i] = NUM2SIZET(v_arg);
               }
               else{
                  StringValue(v_arg);
                  rb_str_modify(v_arg);
                  param.params[i] = (uintptr_t)StringValuePtr(v_arg);
               }
               break;
            case _T_CALLBACK:
               ActiveCallback = v_arg;
               param.params[i] = (LPARAM)NUM2SIZET(rb_iv_get(ActiveCallback, "@address"));;
               break;
            case _T_STRING:
               param.params[i] = (uintptr_t)RSTRING_PTR(v_arg);
               break;
            default:
               param.params[i] = NUM2SIZET(v_arg);
         }
   }

   /* Call the function, get the return value */
   if(strcmp(StringValuePtr(RARRAY_PTR(v_proto)[0]), "V") == 0 && len == 1)
   {
        return_value = ptr->function();
   }
   else
   {
        switch(len)
        {
        case 0:
            return_value = ptr->function();
            break;
        case 1:
            return_value = ptr->function(param.params[0]);
            break;
        case 2:
            return_value = ptr->function(param.params[0], param.params[1]);
            break;
        case 3:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2]);
            break;
        case 4:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3]);
            break;
        case 5:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4]);
            break;
        case 6:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5]);
            break;
        case 7:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6]);
            break;
        case 8:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7]);
            break;
        case 9:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8]);
            break;
        case 10:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9]);
            break;
        case 11:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10]);
            break;
        case 12:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10], param.params[11]);
            break;
        case 13:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10], param.params[11], param.params[12]);
            break;
        case 14:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10], param.params[11], param.params[12], param.params[13]);
            break;
        case 15:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10], param.params[11], param.params[12], param.params[13],
                param.params[14]);
            break;
        case 16:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10], param.params[11], param.params[12], param.params[13],
                param.params[14], param.params[15]);
            break;
        case 17:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10], param.params[11], param.params[12], param.params[13],
                param.params[14], param.params[15], param.params[16]);
            break;
        case 18:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10], param.params[11], param.params[12], param.params[13],
                param.params[14], param.params[15], param.params[16], param.params[17]);
            break;
        case 19:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10], param.params[11], param.params[12], param.params[13],
                param.params[14], param.params[15], param.params[16], param.params[17],
                param.params[18]);
            break;
        case 20:
            return_value = ptr->function(param.params[0], param.params[1],
                param.params[2], param.params[3], param.params[4], param.params[5],
                param.params[6], param.params[7], param.params[8], param.params[9],
                param.params[10], param.params[11], param.params[12], param.params[13],
                param.params[14], param.params[15], param.params[16], param.params[17],
                param.params[18], param.params[19]);
            break;
        default:
            rb_raise(rb_eArgError,"number of parameters exceed 20!");
        }
   }

   /* Return the appropriate type based on the return type specified
    * in the constructor.
    */
   switch(ptr->return_type){
      case _T_INTEGER:
         v_return = INT2NUM(return_value);
         break;
      case _T_LONG:
         v_return = SIZET2NUM(return_value);
         break;
      case _T_VOID:
         v_return = Qnil;
         break;
      case _T_POINTER:
         if(!return_value){
            v_return = Qnil;
         }
         else{
            VALUE v_efunc = rb_iv_get(self, "@effective_function_name");
            char* efunc = RSTRING_PTR(v_efunc);
            if(efunc[strlen(efunc)-1] == 'W'){
               v_return = rb_str_new(
                  (TCHAR*)return_value,
                  wcslen((wchar_t*)return_value)*2
               );
            }
            else{
               v_return = rb_str_new2((TCHAR*)return_value);
            }
         }
         break;
      case _T_STRING:
         {
            VALUE v_efunc = rb_iv_get(self, "@effective_function_name");
            char* efunc = RSTRING_PTR(v_efunc);

            if(efunc[strlen(efunc)-1] == 'W'){
               v_return = rb_str_new(
                  (TCHAR*)return_value,
                  wcslen((wchar_t*)return_value)*2
               );
            }
            else{
               v_return = rb_str_new2((TCHAR*)return_value);
            }
         }
         break;
      default:
         v_return = INT2NUM(0);
   }

   return v_return;
}