1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays sequences kernel accessors math alien.accessors
4 alien.c-types byte-arrays words io io.encodings
5 io.streams.byte-array io.streams.memory io.encodings.utf8
6 io.encodings.utf16 system alien strings cpu.architecture ;
9 GENERIC# alien>string 1 ( c-ptr encoding -- string/f )
12 >r <memory-stream> r> <decoder>
13 "\0" swap stream-read-until drop ;
18 ERROR: invalid-c-string string ;
20 : check-string ( string -- )
21 0 over memq? [ invalid-c-string ] [ drop ] if ;
23 GENERIC# string>alien 1 ( string encoding -- byte-array )
25 M: c-ptr string>alien drop ;
27 M: string string>alien
31 [ 0 swap stream-write1 ]
32 [ stream>> >byte-array ]
35 : malloc-string ( string encoding -- alien )
36 string>alien malloc-byte-array ;
38 PREDICATE: string-type < pair
39 first2 [ "char*" = ] [ word? ] bi* and ;
41 M: string-type c-type ;
43 M: string-type heap-size
44 drop "void*" heap-size ;
46 M: string-type c-type-align
47 drop "void*" c-type-align ;
49 M: string-type c-type-stack-align?
50 drop "void*" c-type-stack-align? ;
52 M: string-type unbox-parameter
53 drop "void*" unbox-parameter ;
55 M: string-type unbox-return
56 drop "void*" unbox-return ;
58 M: string-type box-parameter
59 drop "void*" box-parameter ;
61 M: string-type box-return
62 drop "void*" box-return ;
64 M: string-type stack-size
65 drop "void*" stack-size ;
67 M: string-type c-type-reg-class
70 M: string-type c-type-boxer
71 drop "void*" c-type-boxer ;
73 M: string-type c-type-unboxer
74 drop "void*" c-type-unboxer ;
76 M: string-type c-type-boxer-quot
77 second [ alien>string ] curry [ ] like ;
79 M: string-type c-type-unboxer-quot
80 second [ string>alien ] curry [ ] like ;
82 M: string-type c-type-getter
85 M: string-type c-type-setter
86 drop [ set-alien-cell ] ;
92 : utf16n ( -- descriptor )
93 little-endian? utf16le utf16be ? ; foldable
95 M: utf16n <decoder> drop utf16n <decoder> ;
97 M: utf16n <encoder> drop utf16n <encoder> ;
99 : alien>native-string ( alien -- string )
100 os windows? [ utf16n ] [ utf8 ] if alien>string ;
102 : dll-path ( dll -- string )
103 path>> alien>native-string ;
105 : string>symbol ( str -- alien )
106 [ os wince? [ utf16n ] [ utf8 ] if string>alien ]
107 over string? [ call ] [ map ] if ;
109 { "char*" utf8 } "char*" typedef
110 { "char*" utf16n } "wchar_t*" typedef
111 "char*" "uchar*" typedef