-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths7-ffi.html
3630 lines (3126 loc) · 134 KB
/
s7-ffi.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<!-- documentation for s7 -->
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>s7-ffi</title>
<style>
EM.red {color:red; font-style:normal}
EM.normal {font-style:normal}
EM.redb {color:red; font-weight: bold; font-style: normal}
EM.error {color:chocolate; font-style:normal}
EM.emdef {font-weight: bold; font-style: normal}
EM.green {color:green; font-style:normal}
EM.gray {color:#505050; font-style:normal}
EM.big {font-size: 20px; font-style: normal;}
EM.bigger {font-size: 30px; font-style: normal;}
EM.def {font-style: normal}
H1 {text-align: center}
UL {list-style-type: none}
A {text-decoration:none}
A:hover {text-decoration:underline}
A.def {font-weight: bold;
font-style: normal;
text-decoration:none;
}
PRE.indented {padding-left: 1.0cm;}
DIV.indented {background-color: #F8F8F0;
padding-left: 0.5cm;
padding-right: 0.5cm;
padding-top: 0.5cm;
padding-bottom: 0.5cm;
margin-bottom: 0.5cm;
border: 1px solid gray;
border-radius: 20px;
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
}
DIV.small {font-size: small;
padding-left: 0.5cm;
padding-right: 0.5cm;
padding-bottom: 0.5cm;
}
DIV.header {margin-top: 60px;
margin-bottom: 30px;
border: 4px solid #00ff00; /* green */
background-color: #eefdee; /* lightgreen */
padding-left: 30px;
}
DIV.shortheader {margin-top: 30px;
margin-bottom: 10px;
border: 4px solid #00ff00; /* green */
background-color: #f5f5dc;
padding-left: 30px;
padding-top: 5px;
padding-bottom: 5px;
width: 20%;
}
DIV.topheader {margin-top: 10px;
margin-bottom: 40px;
border: 4px solid #00ff00; /* green */
background-color: #f5f5dc; /* beige */
font-family: 'Helvetica';
font-size: 30px;
text-align: center;
padding-top: 10px;
padding-bottom: 10px;
}
DIV.separator {margin-top: 30px;
margin-bottom: 10px;
border: 2px solid #00ff00; /* green */
background-color: #f5f5dc; /* beige */
padding-top: 4px;
width: 30%;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
}
DIV.smallseparator {margin-top: 10px;
margin-bottom: 10px;
border: 2px solid #00ff00; /* green */
background-color: #f5f5dc; /* beige */
padding-top: 4px;
width: 20%;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
text-align: center;
}
BODY.body {background-color: #ffffff; /* white */
margin-right: 20px;
margin-left: 20px;
}
DIV.listener {background-color: #f0f8ff;
font-family: 'Monospace';
padding-left: 6px;
padding-right: 6px;
padding-bottom: 4px;
margin-left: 1.0cm;
margin-right: 4.0cm;
border: 2px solid #a0a0a0;
}
LI.li_header {padding-top: 20px;}
</style>
</head>
<body class="body">
<div class="topheader" id="FFIexamples">FFI examples</div>
<ul>
<li><a href="s7-ffi.html#repl">read-eval-print loop (and emacs)</a>
<li><a href="s7-ffi.html#defun">define a function with arguments and a returned value, and define a variable </a>
<li><a href="s7-ffi.html#defvar">call a Scheme function from C, and get/set Scheme variable values in C</a>
<li><a href="s7-ffi.html#juce">C++ and Juce</a>
<li><a href="s7-ffi.html#sndlib">load sndlib using the Xen functions and macros</a>
<li><a href="s7-ffi.html#pwstype">add a new Scheme type and a procedure with a setter</a>
<li><a href="s7-ffi.html#functionportexample">redirect display output to a C procedure</a>
<li><a href="s7-ffi.html#extendop">extend a built-in operator ("+" in this case)</a>
<li><a href="s7-ffi.html#definestar1">C-side define* (s7_define_function_star)</a>
<li><a href="s7-ffi.html#definemacro1">C-side define-macro (s7_define_macro)</a>
<li><a href="s7-ffi.html#definegeneric">define a generic function in C</a>
<li><a href="s7-ffi.html#signal">signal handling (C-C to break out of an infinite loop)</a>
<li><a href="s7-ffi.html#notify">notification in C that a Scheme variable has been set!</a>
<li><a href="s7-ffi.html#namespace">Load C defined stuff into a separate namespace</a>
<li><a href="s7-ffi.html#Cerrors">Error handling in C</a>
<li><a href="s7-ffi.html#testhook">Hooks in C and Scheme</a>
<li><a href="s7-ffi.html#dload">Load a C module dynamically</a>
<li><a href="s7-ffi.html#gmpex">gmp and friends</a>
<li><a href="s7-ffi.html#gdb">gdb</a>
<li><a href="s7-ffi.html#webassembly">WASM</a>
<li><a href="s7-ffi.html#ffinotes">FFI notes</a>
</ul>
<p>s7 exists only to serve as an extension of some other application, so
it is primarily a foreign function interface. s7.h has lots of comments about the individual
functions. Here I'll collect some complete examples. s7.c depends on the following
compile-time flags:
</p>
<pre class="indented">
SIZEOF_VOID_P 8 (default) or 4.
WITH_GMP 1 if you want multiprecision arithmetic (requires gmp, mpfr, and mpc, default is 0)
HAVE_COMPLEX_NUMBERS 1 if your compiler supports complex numbers
HAVE_COMPLEX_TRIG 1 if your math library has complex versions of the trig functions
DISABLE_DEPRECATED 1 if you want to make sure you're not using any deprecated s7 stuff (default is 0)
WITH_IMMUTATBLE_UNQUOTE 1 if you want "unquote" omitted (default is 0)
WITH_EXTRA_EXPONENT_MARKERS 1 if you want "d", "f", "l", and "s" in addition to "e" as exponent markers (default is 0)
if someone defends these exponent markers, ask him to read 1l11+11l1i
(in 2 million lines of open-source Scheme, there is not one use of these silly things)
WITH_SYSTEM_EXTRAS 1 if you want some additional OS-related functions built-in (default is 0)
WITH_MAIN 1 if you want s7.c to include a main program section that runs a REPL.
WITH_C_LOADER 1 if you want to be able to load shared object files with load.
</pre>
<p>See the comment at the start of s7.c for more information about these switches.
s7.h defines the two main number types: s7_int and s7_double.
The examples that follow show:
</p>
<ul>
<li><a href="#repl">read-eval-print loop (and emacs)</a>
<li><a href="#defun">define a function with arguments and a returned value, and define a variable </a>
<li><a href="#defvar">call a Scheme function from C, and get/set Scheme variable values in C</a>
<li><a href="#juce">C++ and Juce</a>
<li><a href="#sndlib">load sndlib using the Xen functions and macros</a>
<li><a href="#pwstype">add a new Scheme type and a procedure with a setter</a>
<li><a href="#functionportexample">redirect display output to a C procedure</a>
<li><a href="#extendop">extend a built-in operator ("+" in this case)</a>
<li><a href="#definestar1">C-side define* (s7_define_function_star)</a>
<li><a href="#definemacro1">C-side define-macro (s7_define_macro)</a>
<li><a href="#definegeneric">define a generic function in C</a>
<li><a href="#signal">signal handling (C-C to break out of an infinite loop)</a>
<li><a href="#notify">notification in C that a Scheme variable has been set!</a>
<li><a href="#namespace">Load C defined stuff into a separate namespace</a>
<li><a href="#Cerrors">Error handling in C</a>
<li><a href="#testhook">Hooks in C and Scheme</a>
<li><a href="#dload">Load a C module dynamically</a>
<li><a href="#gmpex">gmp and friends</a>
<li><a href="#gdb">gdb</a>
<li><a href="#webassembly">WASM</a>
</ul>
<div class="header" id="repl"><h4>A simple listener</h4></div>
<div class="indented">
<pre>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "s7.h"
int main(int argc, char **argv)
{
s7_scheme *s7 = <em class=red>s7_init</em>(); /* initialize the interpreter */
while (1) /* fire up a read-eval-print loop */
{
char buffer[512];
fprintf(stdout, "\n> "); /* prompt for input */
fgets(buffer, 512, stdin);
if ((buffer[0] != '\n') ||
(strlen(buffer) > 1))
{ /* evaluate the input and print the result */
char response[1024];
snprintf(response, 1024, "(write %s)", buffer);
<em class=red>s7_eval_c_string</em>(s7, response);
}}
}
/* if not using gcc or clang, make mus-config.h (it can be empty), then
*
* gcc -c s7.c -I.
* gcc -o repl repl.c s7.o -lm -I. -ldl
*
* run it:
*
* repl
* > (+ 1 2)
* <em class="gray">3</em>
* > (define (add1 x) (+ 1 x))
* <em class="gray">add1</em>
* > (add1 2)
* <em class="gray">3</em>
* > (exit)
*
* for long-term happiness in linux use:
* gcc -o repl repl.c s7.o -Wl,-export-dynamic -lm -I. -ldl
* clang also needs -fPIC I think
* freebsd:
* gcc -o repl repl.c s7.o -Wl,-export-dynamic -lm -I.
* osx:
* gcc -o repl repl.c s7.o -lm -I.
* openbsd:
* clang -o repl repl.c s7.o -I. -fPIC -Wl,-export-dynamic -lm
*/
</pre>
</div>
<p>Since this reads stdin and writes stdout, it can be run as a Scheme subjob of emacs.
One (inconvenient) way to do this is to set the emacs variable scheme-program-name to
the name of the exectuable created above ("repl"), then call the emacs function run-scheme:
M-x eval-expression in emacs, followed by (setq scheme-program-name "repl"), then
M-x run-scheme, and you're talking to s7 in emacs. Of course, this connection can be
customized indefinitely. See, for example, inf-snd.el in the Snd package.
</p>
<p>Here are the not-always-built-in indentations I use in emacs:
</p>
<pre class="indented">
(put 'with-let 'scheme-indent-function 1)
(put 'with-baffle 'scheme-indent-function 0)
(put 'with-sound 'scheme-indent-function 1)
(put 'catch 'scheme-indent-function 1)
(put 'lambda* 'scheme-indent-function 1)
(put 'when 'scheme-indent-function 1)
(put 'let-temporarily 'scheme-indent-function 1)
(put 'let*-temporarily 'scheme-indent-function 1)
(put 'call-with-input-string 'scheme-indent-function 1)
(put 'unless 'scheme-indent-function 1)
(put 'letrec* 'scheme-indent-function 1)
(put 'sublet 'scheme-indent-function 1)
(put 'varlet 'scheme-indent-function 1)
(put 'case* 'scheme-indent-function 1)
(put 'macro 'scheme-indent-function 1)
(put 'macro* 'scheme-indent-function 1)
(put 'bacro 'scheme-indent-function 1)
(put 'bacro* 'scheme-indent-function 1)
</pre>
<p>To read stdin while working in a GUI-based program is trickier. In glib, you can use
something like this:
</p>
<blockquote>
<div class="indented">
<pre>
static gboolean read_stdin(GIOChannel *source, GIOCondition condition, gpointer data)
{
/* here read from g_io_channel_unix_get_fd(source) and call s7_eval_string */
return(true);
}
/* ... during initialization ... */
GIOChannel *channel;
channel = g_io_channel_unix_new(STDIN_FILENO); /* watch stdin */
stdin_id = g_io_add_watch_full(channel, /* and call read_stdin above if input is noticed */
G_PRIORITY_DEFAULT,
(GIOCondition)(G_IO_IN | G_IO_HUP | G_IO_ERR),
<em class=red>read_stdin</em>, NULL, NULL);
g_io_channel_unref(channel);
</pre></div>
</blockquote>
<p>Here's a version that uses libtecla for the line editor:
</p>
<blockquote>
<div class="indented">
<pre>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libtecla.h>
#include "s7.h"
int main(int argc, char **argv)
{
GetLine *gl = new_GetLine(500, 5000); /* The tecla line editor */
s7_scheme *s7 = s7_init();
while (1)
{
char *buffer;
buffer = gl_get_line(gl, "> ", NULL, 0);
if ((buffer[0] != '\n') ||
(strlen(buffer) > 1))
{
char response[1024];
snprintf(response, 1024, "(write %s)", buffer);
s7_eval_c_string(s7, response);
fprintf(stdout, "\n");
}}
gl = del_GetLine(gl);
}
/*
* gcc -c s7.c -I. -O2 -g3
* gcc -o ex1 ex1.c s7.o -lm -I. -ltecla -ldl
*/
</pre></div>
</blockquote>
<p>A repl (based on repl.scm or nrepl.scm) is built into s7. Include the compiler flag -DWITH_MAIN:
</p>
<pre class="indented">
gcc -o nrepl s7.c -O2 -I. -Wl,-export-dynamic -lm -ldl -DWITH_MAIN -DWITH_NOTCURSES -lnotcurses-core
</pre>
<p id="beginhook">
Common Lisp has something called "evalhook" that makes it possible
to insert your own function into the eval loop. In s7, we have a "begin_hook" which sits at the opening of many begin blocks
(implicit or explicit). begin_hook is a (C) function;
if it sets its bool argument to true,
s7 interrupts the current evaluation.
Here is a version of the REPL in which begin_hook watches for C-g to interrupt
some long computation:
</p>
<blockquote>
<div class="indented">
<pre>
/* terminal-based REPL,
* an expansion of the <a href="#repl">read-eval-print loop</a> program above.
* type C-g to interrupt an evaluation.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <signal.h>
#include "s7.h"
static struct termios save_buf, buf;
static void sigcatch(int n)
{
/* put things back the way they were */
tcsetattr(fileno(stdin), TCSAFLUSH, &save_buf);
exit(0);
}
static char buffer[512];
static int type_ahead_point = 0;
static void <em class=red>watch_for_c_g</em>(s7_scheme *sc, bool *all_done)
{
char c;
/* watch for C-g without blocking, save other chars as type-ahead */
tcsetattr(fileno(stdin), TCSAFLUSH, &buf);
if (read(fileno(stdin), &c, 1) == 1)
{
if (c == 7) /* C-g */
{
*all_done = true;
type_ahead_point = 0;
}
else buffer[type_ahead_point++] = c;
}
tcsetattr(fileno(stdin), TCSAFLUSH, &save_buf);
}
int main(int argc, char **argv)
{
s7_scheme *s7;
bool use_begin_hook = (tcgetattr(fileno(stdin), &save_buf) >= 0);
if (use_begin_hook)
{
buf = save_buf;
buf.c_lflag &= ~ICANON;
buf.c_cc[VMIN] = 0;
buf.c_cc[VTIME] = 0;
signal(SIGINT, sigcatch);
signal(SIGQUIT, sigcatch);
signal(SIGTERM, sigcatch);
}
s7 = s7_init();
if (argc == 2)
{
fprintf(stderr, "load %s\n", argv[1]);
if (!s7_load(s7, argv[1]))
fprintf(stderr, "can't find %s\n", argv[1]);
}
else
{
while (1)
{
fprintf(stdout, "\n> ");
fgets((char *)(buffer + type_ahead_point), 512 - type_ahead_point, stdin);
type_ahead_point = 0;
if ((buffer[0] != '\n') ||
(strlen(buffer) > 1))
{
char response[1024];
snprintf(response, 1024, "(write %s)", buffer);
if (use_begin_hook)
<em class=red>s7_set_begin_hook</em>(s7, watch_for_c_g);
s7_eval_c_string(s7, response);
if (use_begin_hook)
<em class=red>s7_set_begin_hook</em>(s7, NULL);
}}}
if (use_begin_hook)
tcsetattr(fileno(stdin), TCSAFLUSH, &save_buf);
}
</pre></div>
</blockquote>
<div class="header" id="defun"><h4>Define a function with arguments and a returned value, and a variable</h4></div>
<div class="indented">
<pre>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "s7.h"
static s7_pointer add1(s7_scheme *sc, s7_pointer args)
{
/* all added functions have this form, args is a list,
* s7_car(args) is the first arg, etc
*/
if (<em class=red>s7_is_integer</em>(s7_car(args)))
return(<em class=red>s7_make_integer</em>(sc, 1 + <em class=red>s7_integer</em>(s7_car(args))));
return(s7_wrong_type_arg_error(sc, "add1", 1, s7_car(args), "an integer"));
}
int main(int argc, char **argv)
{
s7_scheme *s7 = s7_init();
s7_define_function(s7, "add1", add1, 1, 0, false, "(add1 int) adds 1 to int");
/* add the function "add1" to the interpreter.
* 1, 0, false -> one required arg,
* no optional args,
* no "rest" arg
*/
<em class=red>s7_define_variable</em>(s7, "my-pi", <em class=red>s7_make_real</em>(s7, 3.14159265));
while (1) /* fire up a "repl" */
{
char buffer[512];
fprintf(stdout, "\n> "); /* prompt for input */
fgets(buffer, 512, stdin);
if ((buffer[0] != '\n') ||
(strlen(buffer) > 1))
{
char response[1024];
snprintf(response, 1024, "(write %s)", buffer);
s7_eval_c_string(s7, response); /* evaluate input and write the result */
}}
}
/* doc7
* > my-pi
* <em class="gray">3.14159265</em>
* > (+ 1 (add1 1))
* <em class="gray">3</em>
* > (exit)
*/
</pre></div>
<div class="header" id="defvar"><h4>Call a Scheme-defined function from C, and get/set Scheme variable values in C</h4></div>
<div class="indented">
<pre>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "s7.h"
int main(int argc, char **argv)
{
s7_scheme *s7 = s7_init();
s7_define_variable(s7, "an-integer", s7_make_integer(s7, 1));
s7_eval_c_string(s7, "(define (add1 a) (+ a 1))");
fprintf(stderr, "an-integer: %lld\n",
s7_integer(<em class=red>s7_name_to_value</em>(s7, "an-integer")));
<em class=red>s7_symbol_set_value</em>(s7, <em class=red>s7_make_symbol</em>(s7, "an-integer"), s7_make_integer(s7, 32));
fprintf(stderr, "now an-integer: %lld\n",
s7_integer(<em class=red>s7_name_to_value</em>(s7, "an-integer")));
fprintf(stderr, "(add1 2): %lld\n",
s7_integer(<em class=red>s7_call</em>(s7,
s7_name_to_value(s7, "add1"),
s7_cons(s7, s7_make_integer(s7, 2), s7_nil(s7)))));
}
/*
* doc7
* an-integer: 1
* now an-integer: 32
* (add1 2): 3
*/
</pre>
<p>In more complicated cases, it is probably easier use s7_eval_c_string_with_environment.
As an example, say we want to have a C procedure that calls the pretty printer function pp
in write.scm, returning a string to C. We need to make sure pp is loaded, and catch
any errors that come up. And we need to pass the C-level s7 object to pp. So...
</p>
<pre>
static const char *pp(s7_scheme *sc, s7_pointer obj) /* (pp obj) */
{
return(s7_string(
<em class=red>s7_eval_c_string_with_environment</em>(sc,
"(catch #t \
(lambda () \
(unless (defined? 'pp) \
(load \"write.scm\")) \
(<em class=red>pp</em> obj)) \
(lambda (type info) \
(apply format #f info)))",
<em class=red>s7_inlet</em>(sc, s7_list(sc, 1, s7_cons(sc, s7_make_symbol(sc, "obj"), obj))))));
}
</pre>
<p>and now when we want a pretty-printed representation of something: pp(sc, obj);
The s7_inlet call is creating a local environment with the object "obj" bound
in scheme to the name "obj" so that (pp obj) will find the "obj" that actually
lives in C. You may need to give the full filename for write.scm, or add its path
to the <a href="s7.html#loadpath">load-path list</a>. In the latter case, <code>(require write.scm)</code> could
replace <code>(unless (defined?...))</code>.
</p>
</div>
<div class="header" id="juce"><h4>C++ and Juce, from Rick Taube</h4></div>
<div class="indented">
<pre>
int main(int argc, const char* argv[])
{
initialiseJuce_NonGUI();
s7_scheme *s7 = s7_init();
if (!s7)
{
std::cout << "Can't start S7!\n";
return -1;
}
while (true)
{
s7_pointer val;
std::string str;
std::cout << "\ns7> ";
std::getline(std::cin, str);
val = s7_eval_c_string(s7, str.c_str());
std::cout << s7_object_to_c_string(s7, val);
}
free(s7);
std::cout << "Bye!\n";
return 0;
}
</pre></div>
<div class="header" id="sndlib"><h4>Load sndlib into an s7 repl</h4></div>
<div class="indented">
<pre>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
/* assume we've configured and built sndlib, so it has created a mus-config.h file.
* also assume we've built s7 with WITH_SYSTEM_EXTRAS set, so we have file-exists? and delete-file
*/
#include "mus-config.h"
#include "s7.h"
#include "xen.h"
#include "clm.h"
#include "clm2xen.h"
/* we need to redirect clm's mus_error calls to s7_error */
static void mus_error_to_s7(int type, char *msg)
{
s7_error(s7, /* s7 is declared in xen.h, defined in xen.c */
s7_make_symbol(s7, "mus-error"),
s7_cons(s7, s7_make_string(s7, msg), s7_nil(s7)));
}
int main(int argc, char **argv)
{
s7 = s7_init(); /* initialize the interpreter */
s7_xen_initialize(s7); /* initialize the xen stuff (hooks and the xen s7 FFI used by sndlib) */
Init_sndlib(); /* initialize sndlib with all the functions linked into s7 */
mus_error_set_handler(mus_error_to_s7); /* catch low-level errors and pass them to s7-error */
while (1) /* fire up a "repl" */
{
char buffer[512];
fprintf(stdout, "\n> "); /* prompt for input */
fgets(buffer, 512, stdin);
if ((buffer[0] != '\n') ||
(strlen(buffer) > 1))
{
char response[1024];
snprintf(response, 1024, "(write %s)", buffer);
s7_eval_c_string(s7, response); /* evaluate input and write the result */
}}
}
/* gcc -o doc7 doc7.c -lm -I. /usr/local/lib/libsndlib.a -lasound -ldl
*
* (load "sndlib-ws.scm")
* (with-sound () (outa 10 .1))
* (load "v.scm")
* (with-sound () (fm-violin 0 .1 440 .1))
*
* you might also need -lgsl -lgslcblas -lfftw3
*/
</pre>
</div>
<p>If you built libsndlib.so, it is possible to use it directly in the s7 repl:
</p>
<pre>
repl ; this is a bare s7 running repl.scm via -DWITH_MAIN=1
loading libc_s7.so
> (load "/home/bil/test/sndlib/libsndlib.so" (inlet 'init_func 's7_init_sndlib))
#t ; s7_init_sndlib ties all the sndlib functions and variables into s7
> (load "sndlib-ws.scm")
tmpnam
> (set! *clm-player* (lambda (file) (system (format #f "sndplay ~A" file))))
> (load "v.scm")
fm-violin
> (with-sound (:play #t) (fm-violin 0 1 440 .1))
"test.snd"
</pre>
<p>You can use autoload to load libsndlib when needed:
</p>
<pre class="indented">
(define (find-library name)
(if (or (file-exists? name)
(char=? (name 0) #\/))
name
(call-with-exit
(lambda (return)
(for-each
(lambda (path)
(let ((new-name (string-append path "/" name)))
(if (file-exists? new-name)
(return new-name))))
*load-path*)
(let ((libs (getenv "LD_LIBRARY_PATH")) ; colon separated directory names
(start 0))
(do ((colon (char-position #\: libs) (char-position #\: libs start)))
((or (not colon)
(let ((new-name (string-append (substring libs start colon) "/" name)))
(and (file-exists? new-name)
(return new-name)))))
(set! start (+ colon 1))))
name))))
(<em class=red>autoload</em> 'clm
(lambda (e)
(load (find-library "libsndlib.so") (inlet '(init_func . s7_init_sndlib)))
(set! *features* (cons 'clm *features*))
(with-let (rootlet) (define clm #t))
(load "sndlib-ws.scm")
(set! *clm-player* (lambda (file) (system (format #f "sndplay ~A" file))))))
</pre>
<p>and use the repl's vt100 stuff to (for example) post the current begin time
as a note list computes:
</p>
<pre class="indented">
(define (clm-notehook . args)
;; assume second arg is begin time (first is instrument name)
(when (and (pair? args)
(pair? (cdr args))
(number? (cadr args)))
(with-let (sublet (*repl* 'repl-let) :begin-time (cadr args))
(let ((coords (cursor-coords))
(col (floor (/ last-col 2))))
(let ((str (number->string begin-time)))
(format *stderr* "~C[~D;~DH" #\escape prompt-row col)
(format *stderr* "~C[K~A" #\escape (if (> (length str) col) (substring str 0 (- col 1)) str)))
(format *stderr* "~C[~D;~DH" #\escape (cdr coords) (car coords))))))
(set! *clm-notehook* clm-notehook)
</pre>
<div class="header" id="pwstype"><h4>Add a new Scheme type and a procedure with a setter</h4></div>
<div class="indented">
<pre>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "s7.h"
/* define *listener-prompt* in scheme, add two accessors for C get/set */
static const char *listener_prompt(s7_scheme *sc)
{
return(s7_string(s7_name_to_value(sc, "*listener-prompt*")));
}
static void set_listener_prompt(s7_scheme *sc, const char *new_prompt)
{
s7_symbol_set_value(sc, s7_make_symbol(sc, "*listener-prompt*"), s7_make_string(sc, new_prompt));
}
/* now add a new type, a struct named "dax" with two fields, a real "x" and a list "data" */
/* since the data field is an s7 object, we'll need to mark it to protect it from the GC */
typedef struct {
s7_double x;
s7_pointer data;
} dax;
static int dax_type_tag = 0;
static s7_pointer dax_to_string(s7_scheme *sc, s7_pointer args)
{
s7_pointer result;
dax *o = (dax *)s7_c_object_value(s7_car(args));
char *data_str = s7_object_to_c_string(sc, o->data);
int data_str_len = strlen(data_str);
char *str = (char *)calloc(data_str_len + 32, sizeof(char));
snprintf(str, data_str_len + 32, "<dax %.3f %s>", o->x, data_str);
free(data_str);
result = s7_make_string(sc, str);
free(str);
return(result);
}
static s7_pointer free_dax(s7_scheme *sc, s7_pointer obj)
{
free(s7_c_object_value(obj));
return(NULL);
}
static s7_pointer mark_dax(s7_scheme *sc, s7_pointer obj)
{
dax *o = (dax *)s7_c_object_value(obj);
s7_mark(o->data);
return(NULL);
}
static s7_pointer make_dax(s7_scheme *sc, s7_pointer args)
{
dax *o = (dax *)malloc(sizeof(dax));
o->x = s7_real(s7_car(args));
if (s7_cdr(args) != s7_nil(sc))
o->data = s7_cadr(args);
else o->data = s7_nil(sc);
return(<em class=red>s7_make_c_object</em>(sc, dax_type_tag, (void *)o));
}
static s7_pointer is_dax(s7_scheme *sc, s7_pointer args)
{
return(s7_make_boolean(sc,
<em class=red>s7_is_c_object</em>(s7_car(args)) &&
<em class=red>s7_c_object_type</em>(s7_car(args)) == dax_type_tag));
}
static s7_pointer dax_x(s7_scheme *sc, s7_pointer args)
{
dax *o = (dax *)<em class=red>s7_c_object_value</em>(s7_car(args));
return(s7_make_real(sc, o->x));
}
static s7_pointer set_dax_x(s7_scheme *sc, s7_pointer args)
{
dax *o = (dax *)s7_c_object_value(s7_car(args));
o->x = s7_real(s7_cadr(args));
return(s7_cadr(args));
}
static s7_pointer dax_data(s7_scheme *sc, s7_pointer args)
{
dax *o = (dax *)s7_c_object_value(s7_car(args));
return(o->data);
}
static s7_pointer set_dax_data(s7_scheme *sc, s7_pointer args)
{
dax *o = (dax *)s7_c_object_value(s7_car(args));
o->data = s7_cadr(args);
return(o->data);
}
static s7_pointer dax_is_equal(s7_scheme *sc, s7_pointer args)
{
dax *d1, *d2;
s7_pointer p1 = s7_car(args);
s7_pointer p2 = s7_cadr(args);
if (p1 == p2)
return(s7_t(sc));
if ((!s7_is_c_object(p2)) ||
(s7_c_object_type(p2) != dax_type_tag))
return(s7_f(sc));
d1 = (dax *)s7_c_object_value(p1);
d2 = (dax *)s7_c_object_value(p2);
return(s7_make_boolean(sc,
(d1->x == d2->x) &&
(s7_is_equal(sc, d1->data, d2->data))));
}
int main(int argc, char **argv)
{
s7_scheme *s7 = s7_init();
s7_define_variable(s7, "*listener-prompt*", s7_make_string(s7, ">"));
dax_type_tag = <em class=red>s7_make_c_type</em>(s7, "dax");
s7_c_type_set_gc_free(s7, dax_type_tag, free_dax);
s7_c_type_set_gc_mark(s7, dax_type_tag, mark_dax);
s7_c_type_set_is_equal(s7, dax_type_tag, dax_is_equal);
s7_c_type_set_to_string(s7, dax_type_tag, dax_to_string);
s7_define_function(s7, "make-dax", make_dax, 2, 0, false, "(make-dax x data) makes a new dax");
s7_define_function(s7, "dax?", is_dax, 1, 0, false, "(dax? anything) returns #t if its argument is a dax object");
s7_define_variable(s7, "dax-x",
<em class=red>s7_dilambda</em>(s7, "dax-x", dax_x, 1, 0, set_dax_x, 2, 0, "dax x field"));
s7_define_variable(s7, "dax-data",
<em class=red>s7_dilambda</em>(s7, "dax-data", dax_data, 1, 0, set_dax_data, 2, 0, "dax data field"));
while (1)
{
char buffer[512];
fprintf(stdout, "\n%s ", listener_prompt(s7));
fgets(buffer, 512, stdin);
if ((buffer[0] != '\n') ||
(strlen(buffer) > 1))
{
char response[1024];
snprintf(response, 1024, "(write %s)", buffer);
s7_eval_c_string(s7, response); /* evaluate input and write the result */
}}
}
/* (in Linux);
* gcc dax.c -o dax -I. -O2 -g s7.o -ldl -lm -Wl,-export-dynamic -Wno-stringop-overflow
* dax
* > *listener-prompt*
* <em class="gray">">"</em>
* > (set! *listener-prompt* ":")
* <em class="gray">":"</em>
* : (define obj (make-dax 1.0 (list 1 2 3)))
* <em class="gray">obj</em>
* : obj
* <em class="gray">#<dax 1.000 (1 2 3)></em>
* : (dax-x obj)
* <em class="gray">1.0</em>
* : (dax-data obj)
* <em class="gray">(1 2 3)</em>
* : (set! (dax-x obj) 123.0)
* <em class="gray">123.0</em>
* : obj
* <em class="gray">#<dax 123.000 (1 2 3)></em>
* : (dax? obj)
* <em class="gray">#t</em>
* : (exit)
*/
</pre></div>
<div class="header" id="functionportexample"><h4>Redirect output (and input) to a C procedure</h4></div>
<div class="indented">
<pre>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "s7.h"
static void my_print(s7_scheme *sc, uint8_t c, s7_pointer port)
{
fprintf(stderr, "[%c] ", c);
}
static s7_pointer my_read(s7_scheme *sc, s7_read_t peek, s7_pointer port)
{
return(<em class=red>s7_make_character</em>(sc, fgetc(stdin)));
}
int main(int argc, char **argv)
{
s7_scheme *s7 = s7_init();
<em class=red>s7_set_current_output_port</em>(s7, <em class=red>s7_open_output_function</em>(s7, my_print));
s7_define_variable(s7, "io-port", <em class=red>s7_open_input_function</em>(s7, my_read));
while (1)
{
char buffer[512];
fprintf(stdout, "\n> ");
fgets(buffer, 512, stdin);
if ((buffer[0] != '\n') ||
(strlen(buffer) > 1))
{
char response[1024];
snprintf(response, 1024, "(write %s)", buffer);
s7_eval_c_string(s7, response);
}}
}
/*
* > (+ 1 2)
* <em class="gray">[3]</em>
* > (display "hiho")
* <em class="gray">[h] [i] [h] [o] [#] [<] [u] [n] [s] [p] [e] [c] [i] [f] [i] [e] [d] [>] </em>
* > (define (add1 x) (+ 1 x))
* <em class="gray">[a] [d] [d] [1] </em>
* > (add1 123)