7707f647c2c306f042a1a93a8c65ec2c5414e63b
[uffi.git] / examples / gettime.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          gettime
6 ;;;; Purpose:       UFFI Example file to get time, use C structures
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Feb 2002
9 ;;;;
10 ;;;; $Id$
11 ;;;;
12 ;;;; This file, part of UFFI, is Copyright (c) 2002 by Kevin M. Rosenberg
13 ;;;;
14 ;;;; UFFI users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;; *************************************************************************
18
19 (in-package :cl-user)
20
21 (uffi:def-foreign-type time-t :unsigned-long)
22
23 (uffi:def-struct tm
24     (sec :int)
25   (min :int)
26   (hour :int)
27   (mday :int)
28   (mon :int)
29   (year :int)
30   (wday :int)
31   (yday :int)
32   (isdst :int))
33
34 (uffi:def-function ("time" c-time) 
35     ((time (* time-t)))
36   :returning time-t)
37
38 (uffi:def-function ("localtime" c-localtime)
39     ((time (* time-t)))
40   :returning (* tm))
41
42 (uffi:def-type time-t :unsigned-long)
43 (uffi:def-type tm-pointer (* tm))
44
45 (defun gettime ()
46    "Returns the local time"
47    (uffi:with-foreign-object (time 'time-t)
48 ;;     (declare (type time-t time))
49      (c-time time)
50      (let ((tm-ptr (the tm-pointer (c-localtime time))))
51        (declare (type tm-pointer tm-ptr))
52        (let ((time-string (format nil "~2d/~2,'0d/~d ~2d:~2,'0d:~2,'0d" 
53                                   (1+ (uffi:get-slot-value tm-ptr 'tm 'mon))
54                                   (uffi:get-slot-value tm-ptr 'tm 'mday)
55                                   (+ 1900 (uffi:get-slot-value tm-ptr 'tm 'year))
56                                   (uffi:get-slot-value tm-ptr 'tm 'hour)
57                                   (uffi:get-slot-value tm-ptr 'tm 'min)
58                                   (uffi:get-slot-value tm-ptr 'tm 'sec)
59                                   )))
60          time-string))))
61
62
63
64
65 #+examples-uffi
66 (format t "~&~A" (gettime))
67
68 #+test-uffi
69 (progn
70   (let ((time (gettime)))
71     (util.test:test (stringp time) t :fail-info "Time is not a string")
72     (util.test:test (plusp (parse-integer time :junk-allowed t))
73                     t
74                     :fail-info "time string does not start with a number")))
75
76