ext/dl/sample/libc.rb


DEFINITIONS

This source file includes following functions.


   1  require "dl/import"
   2  require "dl/struct"
   3  
   4  module LIBC
   5    extend DL::Importable
   6  
   7    begin
   8      dlload "libc.so.6"
   9    rescue
  10      dlload "libc.so.5"
  11    end
  12  
  13    extern "int atoi(char*)"
  14    extern "ibool isdigit(int)"
  15    extern "int gettimeofday(struct timeval *, struct timezone *)"
  16    extern "char* strcat(char*, char*)"
  17    extern "FILE* fopen(char*, char*)"
  18    extern "int fclose(FILE*)"
  19    extern "int fgetc(FILE*)"
  20    extern "int strlen(char*)"
  21    extern "void qsort(void*, int, int, void*)"
  22  
  23    def str_qsort(ary, comp)
  24      len = ary.length
  25      r,rs = qsort(ary, len, DL.sizeof('P'), comp)
  26      return rs[0].to_a('S', len)
  27    end
  28  
  29    Timeval = struct [
  30      "long tv_sec",
  31      "long tv_usec",
  32    ]
  33  
  34    Timezone = struct [
  35      "int tz_minuteswest",
  36      "int tz_dsttime",
  37    ]
  38  
  39    def my_compare(ptr1, ptr2)
  40      ptr1.ptr.to_s <=> ptr2.ptr.to_s
  41    end
  42    COMPARE = callback "int my_compare(char**, char**)"
  43  end
  44  
  45  
  46  $cb1 = DL.callback('IPP'){|ptr1, ptr2|
  47    str1 = ptr1.ptr.to_s
  48    str2 = ptr2.ptr.to_s
  49    str1 <=> str2
  50  }
  51  
  52  p LIBC.atoi("10")
  53  
  54  p LIBC.isdigit(?1)
  55  
  56  p LIBC.isdigit(?a)
  57  
  58  p LIBC.strcat("a", "b")
  59  
  60  ary = ["a","c","b"]
  61  ptr = ary.to_ptr
  62  LIBC.qsort(ptr, ary.length, DL.sizeof('P'), LIBC::COMPARE)
  63  p ptr.to_a('S', ary.length)
  64  
  65  tv = LIBC::Timeval.malloc
  66  tz = LIBC::Timezone.malloc
  67  LIBC.gettimeofday(tv, tz)
  68  
  69  p Time.at(tv.tv_sec)