Remove old CVS $Id$ keyword
[uffi.git] / examples / strtol.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          strtol.cl
6 ;;;; Purpose:       UFFI Example file to strtol, uses pointer arithmetic
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Feb 2002
9 ;;;;
10 ;;;; This file, part of UFFI, is Copyright (c) 2002-2010 by Kevin M. Rosenberg
11 ;;;;
12 ;;;; *************************************************************************
13
14 (in-package :cl-user)
15
16 (uffi:def-foreign-type char-ptr (* :unsigned-char))
17
18 ;; This example does not use :cstring to pass the input string since
19 ;; the routine needs to do pointer arithmetic to see how many characters
20 ;; were parsed
21
22 (uffi:def-function ("strtol" c-strtol)
23     ((nptr char-ptr)
24      (endptr (* char-ptr))
25      (base :int))
26   :returning :long)
27
28 (defun strtol (str &optional (base 10))
29   "Returns a long int from a string. Returns number and condition flag.
30 Condition flag is T if all of string parses as a long, NIL if
31 their was no string at all, or an integer indicating position in string
32 of first non-valid character"
33   (let* ((str-native (uffi:convert-to-foreign-string str))
34          (endptr (uffi:allocate-foreign-object 'char-ptr))
35          (value (c-strtol str-native endptr base))
36          (endptr-value (uffi:deref-pointer endptr 'char-ptr)))
37
38     (unwind-protect
39          (if (uffi:null-pointer-p endptr-value)
40              (values value t)
41              (let ((next-char-value (uffi:deref-pointer endptr-value :unsigned-char))
42                    (chars-parsed (- (uffi:pointer-address endptr-value)
43                                     (uffi:pointer-address str-native))))
44                (cond
45                  ((zerop chars-parsed)
46                   (values nil nil))
47                  ((uffi:null-char-p next-char-value)
48                   (values value t))
49                  (t
50                   (values value chars-parsed)))))
51       (progn
52         (uffi:free-foreign-object str-native)
53         (uffi:free-foreign-object endptr)))))
54
55
56
57 #+examples-uffi
58 (progn
59   (flet ((print-results (str)
60            (multiple-value-bind (result flag) (strtol str)
61              (format t "~&(strtol ~S) => ~S,~S" str result flag))))
62     (print-results "55")
63     (print-results "55.3")
64     (print-results "a")))
65
66 #+test-uffi
67 (progn
68   (flet ((test-strtol (str results)
69            (util.test:test (multiple-value-list (strtol str)) results
70                            :test #'equal
71                            :fail-info "Error testing strtol")))
72     (test-strtol "123" '(123 t))
73     (test-strtol "0" '(0 t))
74     (test-strtol "55a" '(55 2))
75     (test-strtol "a" '(nil nil))))
76
77
78