Making Samples executable. #!/usr/bin/env io and chmod a+x *.io
[io/quag.git] / addons / CFFI / samples / LibC.io
blobe1c9fc96d396f77f870fa1eec0f2dea1749119c6
1 #!/usr/bin/env io
3 /* CFFI - A C function interface for Io
4 Copyright (c) 2006 Trevor Fancher. All rights reserved.
5 All code licensed under the New BSD license.
6 */
8 CFFI
10 LibC := Object clone do(
11 Types := Object clone do(
12 appendProto(CFFI Types)
14 Size_t := Long
15 Time_t := Long
17 Tm := Structure clone do(
18 appendProto(Types)
20 appendElement("second", Int)
21 appendElement("minute", Int)
22 appendElement("hour", Int)
23 appendElement("date", Int)
24 appendElement("month", Int)
25 appendElement("year", Int)
26 appendElement("dayOfWeek", Int)
27 appendElement("dayOfYear", Int)
28 appendElement("isDST", Int)
29 appendElement("gmtOffset", Long)
30 appendElement("timezone", CString)
35 _functions := method(
36 _functions = Map clone do(
37 appendProto(LibC Types)
39 lib := Library clone setName("libSystem.dylib")
41 add := method(name, retType, argTypeList,
42 atPut(name, Function clone setLibrary(lib) setName(name) setReturnType(retType) setArgumentTypes(argTypeList))
45 add("strlen", Long, list(CString))
46 add("strchr", CString, list(CString, Char))
47 add("time", Time_t, list(Time_t ptr))
48 //add("localtime", Tm ptr, list(Time_t ptr))
49 add("malloc", Void ptr, list(Size_t))
50 add("free", Void, list(Void ptr))
54 forward := method(
55 m := Message clone setName("call") setArguments(call message arguments)
56 m doInContext(_functions at(call message name))
60 //need to be able to set address on Pointer so malloc will work
61 appendProto(LibC Types)
63 t1 := LibC malloc(Size_t clone setValue(15))
64 t1 setTypeString("^l")
65 t1 pointedToType = Long
67 t2 := LibC time(t1)
69 List clone do(
70 append(t1 value == t2); LibC free(t1)
71 append(LibC strlen("12345") == 5)
72 append(LibC strchr("^^1^^2^^3", Char clone setValue("2")) == "2^^3")
73 ) contains(false) ifTrue(
74 "failure" println
75 ) ifFalse(
76 "success" println