Debian Codegraph @

embedded/man/files/critcl_howto_use.n

raw
1 '\"
2 '\" Generated from file 'critcl_howto_use\&.man' by tcllib/doctools with format 'nroff'
3 '\" Copyright (c) Jean-Claude Wippler
4 '\" Copyright (c) Steve Landers
5 '\" Copyright (c) 2011-2024 Andreas Kupries
6 '\"
7 .TH "critcl_howto_use" n 3\&.3\&.1 doc "C Runtime In Tcl (CriTcl)"
8 .\" The -*- nroff -*- definitions below are for supplemental macros used
9 .\" in Tcl/Tk manual entries.
10 .\"
11 .\" .AP type name in/out ?indent?
12 .\" Start paragraph describing an argument to a library procedure.
13 .\" type is type of argument (int, etc.), in/out is either "in", "out",
14 .\" or "in/out" to describe whether procedure reads or modifies arg,
15 .\" and indent is equivalent to second arg of .IP (shouldn't ever be
16 .\" needed; use .AS below instead)
17 .\"
18 .\" .AS ?type? ?name?
19 .\" Give maximum sizes of arguments for setting tab stops. Type and
20 .\" name are examples of largest possible arguments that will be passed
21 .\" to .AP later. If args are omitted, default tab stops are used.
22 .\"
23 .\" .BS
24 .\" Start box enclosure. From here until next .BE, everything will be
25 .\" enclosed in one large box.
26 .\"
27 .\" .BE
28 .\" End of box enclosure.
29 .\"
30 .\" .CS
31 .\" Begin code excerpt.
32 .\"
33 .\" .CE
34 .\" End code excerpt.
35 .\"
36 .\" .VS ?version? ?br?
37 .\" Begin vertical sidebar, for use in marking newly-changed parts
38 .\" of man pages. The first argument is ignored and used for recording
39 .\" the version when the .VS was added, so that the sidebars can be
40 .\" found and removed when they reach a certain age. If another argument
41 .\" is present, then a line break is forced before starting the sidebar.
42 .\"
43 .\" .VE
44 .\" End of vertical sidebar.
45 .\"
46 .\" .DS
47 .\" Begin an indented unfilled display.
48 .\"
49 .\" .DE
50 .\" End of indented unfilled display.
51 .\"
52 .\" .SO ?manpage?
53 .\" Start of list of standard options for a Tk widget. The manpage
54 .\" argument defines where to look up the standard options; if
55 .\" omitted, defaults to "options". The options follow on successive
56 .\" lines, in three columns separated by tabs.
57 .\"
58 .\" .SE
59 .\" End of list of standard options for a Tk widget.
60 .\"
61 .\" .OP cmdName dbName dbClass
62 .\" Start of description of a specific option. cmdName gives the
63 .\" option's name as specified in the class command, dbName gives
64 .\" the option's name in the option database, and dbClass gives
65 .\" the option's class in the option database.
66 .\"
67 .\" .UL arg1 arg2
68 .\" Print arg1 underlined, then print arg2 normally.
69 .\"
70 .\" .QW arg1 ?arg2?
71 .\" Print arg1 in quotes, then arg2 normally (for trailing punctuation).
72 .\"
73 .\" .PQ arg1 ?arg2?
74 .\" Print an open parenthesis, arg1 in quotes, then arg2 normally
75 .\" (for trailing punctuation) and then a closing parenthesis.
76 .\"
77 .\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
78 .if t .wh -1.3i ^B
79 .nr ^l \n(.l
80 .ad b
81 .\" # Start an argument description
82 .de AP
83 .ie !"\\$4"" .TP \\$4
84 .el \{\
85 . ie !"\\$2"" .TP \\n()Cu
86 . el .TP 15
87 .\}
88 .ta \\n()Au \\n()Bu
89 .ie !"\\$3"" \{\
90 \&\\$1 \\fI\\$2\\fP (\\$3)
91 .\".b
92 .\}
93 .el \{\
94 .br
95 .ie !"\\$2"" \{\
96 \&\\$1 \\fI\\$2\\fP
97 .\}
98 .el \{\
99 \&\\fI\\$1\\fP
100 .\}
101 .\}
102 ..
103 .\" # define tabbing values for .AP
104 .de AS
105 .nr )A 10n
106 .if !"\\$1"" .nr )A \\w'\\$1'u+3n
107 .nr )B \\n()Au+15n
108 .\"
109 .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
110 .nr )C \\n()Bu+\\w'(in/out)'u+2n
111 ..
112 .AS Tcl_Interp Tcl_CreateInterp in/out
113 .\" # BS - start boxed text
114 .\" # ^y = starting y location
115 .\" # ^b = 1
116 .de BS
117 .br
118 .mk ^y
119 .nr ^b 1u
120 .if n .nf
121 .if n .ti 0
122 .if n \l'\\n(.lu\(ul'
123 .if n .fi
124 ..
125 .\" # BE - end boxed text (draw box now)
126 .de BE
127 .nf
128 .ti 0
129 .mk ^t
130 .ie n \l'\\n(^lu\(ul'
131 .el \{\
132 .\" Draw four-sided box normally, but don't draw top of
133 .\" box if the box started on an earlier page.
134 .ie !\\n(^b-1 \{\
135 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
136 .\}
137 .el \}\
138 \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
139 .\}
140 .\}
141 .fi
142 .br
143 .nr ^b 0
144 ..
145 .\" # VS - start vertical sidebar
146 .\" # ^Y = starting y location
147 .\" # ^v = 1 (for troff; for nroff this doesn't matter)
148 .de VS
149 .if !"\\$2"" .br
150 .mk ^Y
151 .ie n 'mc \s12\(br\s0
152 .el .nr ^v 1u
153 ..
154 .\" # VE - end of vertical sidebar
155 .de VE
156 .ie n 'mc
157 .el \{\
158 .ev 2
159 .nf
160 .ti 0
161 .mk ^t
162 \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
163 .sp -1
164 .fi
165 .ev
166 .\}
167 .nr ^v 0
168 ..
169 .\" # Special macro to handle page bottom: finish off current
170 .\" # box/sidebar if in box/sidebar mode, then invoked standard
171 .\" # page bottom macro.
172 .de ^B
173 .ev 2
174 'ti 0
175 'nf
176 .mk ^t
177 .if \\n(^b \{\
178 .\" Draw three-sided box if this is the box's first page,
179 .\" draw two sides but no top otherwise.
180 .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
181 .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
182 .\}
183 .if \\n(^v \{\
184 .nr ^x \\n(^tu+1v-\\n(^Yu
185 \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
186 .\}
187 .bp
188 'fi
189 .ev
190 .if \\n(^b \{\
191 .mk ^y
192 .nr ^b 2
193 .\}
194 .if \\n(^v \{\
195 .mk ^Y
196 .\}
197 ..
198 .\" # DS - begin display
199 .de DS
200 .RS
201 .nf
202 .sp
203 ..
204 .\" # DE - end display
205 .de DE
206 .fi
207 .RE
208 .sp
209 ..
210 .\" # SO - start of list of standard options
211 .de SO
212 'ie '\\$1'' .ds So \\fBoptions\\fR
213 'el .ds So \\fB\\$1\\fR
214 .SH "STANDARD OPTIONS"
215 .LP
216 .nf
217 .ta 5.5c 11c
218 .ft B
219 ..
220 .\" # SE - end of list of standard options
221 .de SE
222 .fi
223 .ft R
224 .LP
225 See the \\*(So manual entry for details on the standard options.
226 ..
227 .\" # OP - start of full description for a single option
228 .de OP
229 .LP
230 .nf
231 .ta 4c
232 Command-Line Name: \\fB\\$1\\fR
233 Database Name: \\fB\\$2\\fR
234 Database Class: \\fB\\$3\\fR
235 .fi
236 .IP
237 ..
238 .\" # CS - begin code excerpt
239 .de CS
240 .RS
241 .nf
242 .ta .25i .5i .75i 1i
243 ..
244 .\" # CE - end code excerpt
245 .de CE
246 .fi
247 .RE
248 ..
249 .\" # UL - underline word
250 .de UL
251 \\$1\l'|0\(ul'\\$2
252 ..
253 .\" # QW - apply quotation marks to word
254 .de QW
255 .ie '\\*(lq'"' ``\\$1''\\$2
256 .\"" fix emacs highlighting
257 .el \\*(lq\\$1\\*(rq\\$2
258 ..
259 .\" # PQ - apply parens and quotation marks to word
260 .de PQ
261 .ie '\\*(lq'"' (``\\$1''\\$2)\\$3
262 .\"" fix emacs highlighting
263 .el (\\*(lq\\$1\\*(rq\\$2)\\$3
264 ..
265 .\" # QR - quoted range
266 .de QR
267 .ie '\\*(lq'"' ``\\$1''\\-``\\$2''\\$3
268 .\"" fix emacs highlighting
269 .el \\*(lq\\$1\\*(rq\\-\\*(lq\\$2\\*(rq\\$3
270 ..
271 .\" # MT - "empty" string
272 .de MT
273 .QW ""
274 ..
275 .BS
276 .SH NAME
277 critcl_howto_use \- How To Use CriTcl
278 .SH DESCRIPTION
279 .PP
280 Be welcome to the \fIC Runtime In Tcl\fR (short: \fICriTcl\fR), a system for embedding and using C
281 code from within \fITcl\fR [http://core\&.tcl-lang\&.org/tcl] scripts\&.
282 .PP
283 This document assumes the presence of a working \fICriTcl\fR installation\&.
284 .PP
285 If that is missing follow the instructions on \fIHow To Install CriTcl\fR\&.
286 .SH BASICS
287 To create a minimal working package
288 .IP [1]
289 Choose a directory to develop in and make it the working directory\&. This should
290 not be a checkout of \fICriTcl\fR itself\&.
291 .IP [2]
292 Save the following example to a file\&. In the following it is assumed that the file
293 was named "\fIexample\&.tcl\fR"\&.
294 .CS
295
296
297 # -*- tcl -*-
298 # Critcl support, absolutely necessary\&.
299 package require critcl
300
301 # Bail out early if the compile environment is not suitable\&.
302 if {![critcl::compiling]} {
303 error "Unable to build project, no proper compiler found\&."
304 }
305
306 # Information for the teapot\&.txt meta data file put into a generated package\&.
307 # Free form strings\&.
308 critcl::license {Andreas Kupries} {Under a BSD license}
309
310 critcl::summary {The first CriTcl-based package}
311
312 critcl::description {
313 This package is the first example of a CriTcl-based package\&. It contains all the
314 necessary and conventionally useful pieces\&.
315 }
316
317 critcl::subject example {critcl package}
318 critcl::subject {basic critcl}
319
320 # Minimal Tcl version the package should load into\&.
321 critcl::tcl 8\&.6
322
323 # Use to activate Tcl memory debugging
324 #critcl::debug memory
325 # Use to activate building and linking with symbols (for gdb, etc\&.)
326 #critcl::debug symbols
327
328 # ## #### ######### ################ #########################
329 ## A hello world, directly printed to stdout\&. Bypasses Tcl's channel system\&.
330
331 critcl::cproc hello {} void {
332 printf("hello world\\n");
333 }
334
335 # ## #### ######### ################ #########################
336
337 # Forcing compilation, link, and loading now\&.
338 critcl::msg -nonewline { Building \&.\&.\&.}
339 if {![critcl::load]} {
340 error "Building and loading the project failed\&."
341 }
342
343 # Name and version the package\&. Just like for every kind of Tcl package\&.
344 package provide critcl-example 1
345
346
347 .CE
348 .IP [3]
349 Invoke the command
350 .CS
351
352 critcl -keep -debug all -pkg example\&.tcl
353 .CE
354 .sp
355 This compiles the example and installs it into a "\fIlib/\fR" sub directory of the
356 working directory, generating output similar to
357 .CS
358
359
360 Config: linux-x86_64-gcc
361 Build: linux-x86_64-gcc
362 Target: linux-x86_64
363 Source: example\&.tcl (provide critcl-example 1) Building \&.\&.\&.
364 Library: example\&.so
365 (tclStubsPtr => const TclStubs *tclStubsPtr;)
366 (tclPlatStubsPtr => const TclPlatStubs *tclPlatStubsPtr;)
367 Package: lib/example
368 Files left in /home/aku/\&.critcl/pkg2567272\&.1644845439
369
370 .CE
371 .IP
372 during operation\&.
373 .sp
374 The \fB-keep\fR option suppressed the cleanup of the generated C files, object
375 files, compiler log, etc\&. normally done at the end of building\&.
376 .CS
377
378
379 % ls -l /home/aku/\&.critcl/pkg2567272\&.1644845439
380 total 36
381 -rw-r--r-- 1 aku aku 1260 Feb 14 18:30 v3118_00000000000000000000000000000004\&.c
382 -rw-r--r-- 1 aku aku 2096 Feb 14 18:30 v3118_00000000000000000000000000000004_pic\&.o
383 -rw-r--r-- 1 aku aku 1728 Feb 14 18:30 v3118_00000000000000000000000000000009\&.c
384 -rw-r--r-- 1 aku aku 2448 Feb 14 18:30 v3118_00000000000000000000000000000009_pic\&.o
385 -rwxr-xr-x 1 aku aku 14424 Feb 14 18:30 v3118_00000000000000000000000000000009\&.so
386 -rw-r--r-- 1 aku aku 1725 Feb 14 18:30 v3118\&.log
387
388 .CE
389 .IP
390 This enables inspection of the generated C code\&.
391 Simply drop the option from the command if that is not desired\&.
392 .sp
393 The option \fB-debug\fR, with argument \fBall\fR activated Tcl's memory
394 debugging and caused the generation of the symbol tables needed by \fBgdb\fR or any
395 other debugger\&. The alternate arguments \fBmemory\fR and \fBsymbols\fR activate just
396 one of the these\&.
397 .IP [4]
398 Now invoke an interactive \fBtclsh\fR and enter the commands:
399 .RS
400 .IP \(bu
401 \fIlappend auto_path lib\fR
402 .IP \(bu
403 \fIpackage require critcl-example\fR
404 .IP \(bu
405 \fIinfo loaded\fR
406 .IP \(bu
407 \fIhello\fR
408 .IP \(bu
409 \fIexit\fR
410 .RE
411 .IP
412 I\&.e\&. extend \fBtclsh\fR's package search path to include the location of the new
413 package, load the package, verify that the associated shared library is present, invoke
414 the package command, and stop the session\&.
415 .sp
416 When the package command is invoked the terminal will show \fBhello world\fR,
417 followed by the prompt\&.
418 .PP
419 .PP
420 Commands: \fIcritcl::compiling\fR, \fIcritcl::cproc\fR,
421 \fIcritcl::description\fR, \fIcritcl::license\fR, \fIcritcl::load\fR,
422 \fIcritcl::msg\fR, \fIcritcl::subject\fR, \fIcritcl::summary\fR, \fIcritcl::tcl\fR\&.
423 .PP
424 Make a copy of "\fIexample\&.tcl\fR" before going through the sub-sections\&. Keep it as
425 a save point to return to from the editing done in the sub-section\&.
426 .SS "SIMPLE ARGUMENTS"
427 A function taking neither arguments nor returning results is not very useful\&.
428 .IP [1]
429 We are now extending the command to take an argument\&.
430 .IP [2]
431 Starting from the \fBBasics\fR\&.
432 Edit the file "\fIexample\&.tcl\fR"\&.
433 Remove the definition of \fBhello\fR\&. Replace it with
434 .CS
435
436
437 critcl::cproc hello {double x} void {
438 /* double x; */
439 printf("hello world, we have %f\\n", x);
440 }
441
442 .CE
443 .IP and rebuild the package\&.
444 .IP [3]
445 When testing the package again, entering the simple \fBhello\fR will fail\&.
446 .sp
447 The changed command is now expecting an argument, and we gave it none\&.
448 .sp
449 Retry by entering
450 .CS
451
452 hello 5
453 .CE
454 .IP instead\&.
455 Now the command behaves as expected and prints the provided value\&.
456 .sp
457 Further try and enter
458 .CS
459
460 hello world
461 .CE
462 .IP
463 This will fail again\&.
464 The command expected a real number and we gave it something decidedly not so\&.
465 .sp
466 These checks (argument count, argument type) are implemented in the translation
467 layer \fICriTcl\fR generates for the C function\&. The function body is never invoked\&.
468 .PP
469 .SS "SIMPLE RESULTS"
470 A function taking neither arguments nor returning results is not very useful\&.
471 .IP [1]
472 We are now extending the command to return a result\&.
473 .IP [2]
474 Starting from the \fBBasics\fR\&.
475 Edit the file "\fIexample\&.tcl\fR"\&.
476 Remove the definition of \fBhello\fR\&. Replace it with
477 .CS
478
479
480 critcl::cproc twice {double x} double {
481 return 2*x;
482 }
483
484 .CE
485 .IP and rebuild the package\&.
486 .IP [3]
487 Note that the name of the command changed\&. Goodbye \fBhello\fR, hello \fBtwice\fR\&.
488 .IP [4]
489 Invoke
490 .CS
491
492 twice 4
493 .CE
494 .IP and the \fBtclsh\fR will print the result \fB8\fR
495 in the terminal\&.
496 .PP
497 .PP
498 An important limitation of the commands implemented so far is that they cannot
499 fail\&. The types used so far (\fBvoid\fR, \fBdouble\fR) and related scalar types can
500 return only a value of the specified type, and nothing else\&. They have no ability to
501 signal an error to the Tcl script\&.
502 .PP
503 We will come back to this after knowing a bit more about the more complex argument
504 and result types\&.
505 .PP
506 Of interest to the eager reader: \fICriTcl cproc Type Reference\fR
507 .SS "RANGE-LIMITED SIMPLE ARGUMENTS"
508 .IP [1]
509 Starting from the \fBBasics\fR\&.
510 Edit the file "\fIexample\&.tcl\fR"\&.
511 Remove the definition of \fBhello\fR\&. Replace it with
512 .CS
513
514
515 critcl::cproc hello {{double > 5 < 22} x} void {
516 /* double x, range 6-21; */
517 printf("hello world, we have %f\\n", x);
518 }
519
520 .CE
521 .IP and rebuild the package\&.
522 .IP [2]
523 When dealing with simple arguments whose range of legal values is limited to a single
524 continuous interval extend the base type with the necessary relations (\fB>\fR, \fB>=\fR,
525 \fB<\fR, and \fB<=\fR) and limiting values\&.
526 .sp
527 \fINote\fR that the limiting values have to be proper constant numbers acceptable by the
528 base type\&. Symbolic values are not accepted\&.
529 .sp
530 Here the argument \fIx\fR of the changed function will reject all values outside of the
531 interval 6 to 21\&.
532 .PP
533 .SS "STRING ARGUMENTS"
534 Tcl prides itself on the fact that \fIEverything Is A String\fR\&.
535 So how are string values passed into C functions ?
536 .IP [1]
537 We are now extending the command with a string argument\&.
538 .IP [2]
539 Starting from the \fBBasics\fR\&.
540 Edit the file "\fIexample\&.tcl\fR"\&.
541 Remove the definition of \fBhello\fR\&. Replace it with
542 .CS
543
544
545 critcl::cproc hello {pstring x} void {
546 /* critcl_pstring x (\&.s, \&.len, \&.o); */
547 printf("hello world, from %s (%d bytes)\\n", x\&.s, x\&.len);
548 }
549
550 .CE
551 .IP and rebuild the package\&.
552 .IP [3]
553 Testing \fBhello\fR with any kind of argument the information is printed\&.
554 .IP [4]
555 Of note here is that the command argument \fBx\fR is a structure\&.
556 .IP [5]
557 The example uses only two of the three fields, the pointer to the string data
558 (\fB\&.s\fR), and the length of the string (\fB\&.len\fR)\&. In bytes, \fInot\fR in
559 characters, because Tcl's internal representation of strings uses a modified UTF-8
560 encoding\&. A character consists of between 1 and \fBTCL_UTF_MAX\fR bytes\&.
561 .IP [6]
562 \fIAttention\fR The pointers (\fB\&.s\fR) refer into data structures \fIinternal\fR
563 to and managed by the Tcl interpreter\&.
564 Changing them is highly likely to cause subtle and difficult to track down bugs\&.
565 Any and all complex arguments must be treated as \fIRead-Only\fR\&. Never modify them\&.
566 .IP [7]
567 Use the simpler type \fBchar*\fR if and only if the length of the string is not
568 relevant to the command, i\&.e\&. not computed, or not used by any of the functions called
569 from the body of the command\&.
570 Its value is essentially just the \fB\&.s\fR field of \fBpstring\fR's structure\&.
571 This then looks like
572 .CS
573
574
575 critcl::cproc hello {char* x} void {
576 /* char* x; */
577 printf("hello world, from %s\\n", x);
578 }
579
580 .CE
581 .PP
582 .SS "STRING RESULTS"
583 Tcl prides itself on the fact that \fIEverything Is A String\fR\&.
584 So how are string values returned from C functions ?
585 .IP [1]
586 We are now giving the command a string result\&.
587 .IP [2]
588 Starting from the \fBBasics\fR\&.
589 Edit the file "\fIexample\&.tcl\fR"\&.
590 Remove the definition of \fBhello\fR\&. Replace it with
591 .CS
592
593
594 critcl::cproc twice {double x} char* {
595 char buf [lb]40[rb];
596 sprintf(buf, "%f", 2*x);
597 return buf;
598 }
599
600 .CE
601 .IP and rebuild the package\&.
602 .IP [3]
603 Note that the name of the command changed\&. Goodbye \fBhello\fR, hello \fBtwice\fR\&.
604 .IP [4]
605 Invoke
606 .CS
607
608 twice 4
609 .CE
610 .IP and the \fBtclsh\fR will print the result \fB8\fR
611 in the terminal\&.
612 .IP [5]
613 \fIAttention\fR\&. To the translation layer the string pointer is owned by the C
614 code\&. A copy is made to become the result seen by Tcl\&.
615 .sp
616 While the C code is certainly allowed to allocate the string on the heap if it so
617 wishes, this comes with the responsibility to free the string as well\&. Abrogation of that
618 responsibility will cause memory leaks\&.
619 .sp
620 The type \fBchar*\fR is recommended to be used with static string buffers, string
621 constants and the like\&.
622 .IP [6]
623 Conversely, to return heap-allocated strings it is recommended to use the type
624 \fBstring\fR instead\&.
625 .sp
626 Replace the definition of \fBtwice\fR with
627 .CS
628
629
630 critcl::cproc twice {double x} string {
631 char* buf = Tcl_Alloc (40);
632 sprintf(buf, "%f", 2*x);
633 return buf;
634 }
635
636 .CE
637 .sp
638 Now the translation layer takes ownership of the string from the C code and
639 transfers that ownership to the Tcl interpreter\&. This means that the string will be
640 released when the Tcl interpreter is done with it\&. The C code has no say in the lifecycle
641 of the string any longer, and having the C code releasing the string \fIwill\fR cause
642 issues\&. Dangling pointers and associated memory corruption and crashes\&.
643 .PP
644 .SS "LIST ARGUMENTS"
645 Even as a string-oriented language Tcl is capable of handling more complex structures\&. The first of
646 it, with Tcl since the beginning are \fIlists\fR\&. Sets of values indexed by a numeric value\&.
647 .PP
648 In C parlance, \fIarrays\fR\&.
649 .IP [1]
650 We are now extending the command with a \fBlist\fR argument\&.
651 .IP [2]
652 Starting from the \fBBasics\fR\&.
653 Edit the file "\fIexample\&.tcl\fR"\&.
654 Remove the definition of \fBhello\fR\&. Replace it with
655 .CS
656
657
658 critcl::cproc hello {list x} void {
659 /* critcl_list x (\&.o, \&.v, \&.c); */
660 printf("hello world, %d elements in (%s)\\n", x\&.c, Tcl_GetString (x\&.o));
661 }
662
663 .CE
664 .IP and rebuild the package\&.
665 .IP [3]
666 Testing \fBhello\fR with any kind of list argument it will print basic information about it\&.
667 .IP [4]
668 Of note here is that the command argument \fBx\fR is a structure\&.
669 .IP [5]
670 The example uses only two of the three fields, the pointer to the original \fBTcl_Obj*\fR
671 holding the list (\fB\&.o\fR), and the length of the list (\fB\&.c\fR) in elements\&.
672 .sp
673 The field \fB\&.v\fR, not used above, is the C array holding the \fBTcl_Obj*\fR pointers to
674 the list elements\&.
675 .IP [6]
676 \fIAttention\fR The pointers \fB\&.o\fR and \fB\&.v\fR refer into data structures
677 \fIinternal\fR to and managed by the Tcl interpreter\&.
678 Changing them is highly likely to cause subtle and difficult to track down bugs\&.
679 Any and all complex arguments must be treated as \fIRead-Only\fR\&. Never modify them\&.
680 .IP [7]
681 As a last note, this argument type does not place any constraints on the size of the list, or
682 on the type of the elements\&.
683 .PP
684 .SS "CONSTRAINED LIST ARGUMENTS"
685 As mentioned at the end of section \fBList Arguments\fR the basic \fBlist\fR type places no
686 constraints on the size of the list, nor on the type of the elements\&.
687 .PP
688 Both kind of constraints can be done however, alone or together\&.
689 .IP [1]
690 We are now extending the command with a length-limited list\&.
691 .IP [2]
692 Starting from the \fBBasics\fR\&.
693 Edit the file "\fIexample\&.tcl\fR"\&.
694 Remove the definition of \fBhello\fR\&. Replace it with
695 .CS
696
697
698 critcl::cproc hello {[5] x} void {
699 /* critcl_list x (\&.o, \&.v, \&.c); */
700 printf("hello world, %d elements in (%s)\\n", x\&.c, Tcl_GetString (x\&.o));
701 }
702
703 .CE
704 .IP and rebuild the package\&.
705 .IP [3]
706 Testing the new command will show that only lists holding exactly \fB5\fR elements will be
707 accepted\&.
708 .IP [4]
709 To accept lists of any length use \fB[]\fR or \fB[*]\fR\&. Both forms are actually
710 aliases of the base type, i\&.e\&. \fBlist\fR\&.
711 .IP [5]
712 To constrain just the type of elements, for example to type \fBint\fR, use
713 .CS
714
715 int[]
716 .CE
717 .IP
718 or
719 .CS
720
721 []int
722 .CE
723 .IP [6]
724 To combine both type and length constraints use the forms
725 .CS
726
727 int[5]
728 .CE
729 .IP or
730 .CS
731
732 [5]int
733 .CE
734 .IP [7]
735 The last, most C-like forms of these contraints place the list indicator syntax on the
736 argument instead of the type\&. I\&.e
737 .CS
738
739 int a[]
740 .CE
741 .IP or
742 .CS
743
744 int a[5]
745 .CE
746 .PP
747 .SS "RAW TCL_OBJ* ARGUMENTS"
748 When the set of predefined argument types is not enough the oldest way of handling the
749 situation is falling back to the structures used by Tcl to manage values, i\&.e\&.
750 \fBTcl_Obj*\fR\&.
751 .IP [1]
752 Starting from the \fBBasics\fR\&.
753 Edit the file "\fIexample\&.tcl\fR"\&.
754 Remove the definition of \fBhello\fR\&. Replace it with
755 .CS
756
757
758 critcl::cproc hello {object x} void {
759 /* Tcl_Obj* x */
760 int len;
761 char* str = Tcl_GetStringFromObj (x, &len);
762 printf("hello world, from %s (%d bytes)\\n", str, len);
763 }
764
765 .CE
766 .IP and rebuild the package\&.
767 .IP [2]
768 Having direct access to the raw \fBTcl_Obj*\fR value all functions of the public
769 Tcl API for working with Tcl values become usable\&. The downside of that is that all the
770 considerations for handling them apply as well\&.
771 .sp
772 In other words, the C code becomes responsible for handling the reference counts
773 correctly, for duplicating shared \fBTcl_Obj*\fR structures before modifying them, etc\&.
774 .sp
775 One thing the C code is allowed to do without restriction is to \fIshimmer\fR the
776 internal representation of the value as needed, through the associated Tcl API
777 functions\&. For example \fBTcl_GetWideIntFromObj\fR and the like\&.
778 It actually has to be allowed to do so, as the type checking done as part of such
779 conversions is now the responsibility of the C code as well\&.
780 .sp
781 For the predefined types this is all hidden in the translation layer generated by
782 \fICriTcl\fR\&.
783 .sp
784 If more than one command has to perform the same kind of checking and/or conversion
785 it is recommended to move the core of the code into proper C functions for proper sharing
786 among the commands\&.
787 .IP [3]
788 This is best done by defining a custom argument type using \fICriTcl\fR commands\&.
789 This extends the translation layer \fICriTcl\fR is able to generate\&.
790 The necessary conversions, type checks, etc\&. are then again hidden from the bulk of the
791 application C code\&.
792 .sp
793 We will come back to this\&.
794 .PP
795 .SS "RAW TCL_OBJ* RESULTS"
796 When the set of predefined result types is not enough the oldest way of handling the
797 situation is falling back to the structures used by Tcl to manage values, i\&.e\&.
798 \fBTcl_Obj*\fR\&.
799 .PP
800 Two builtin types are provided for this, to handle different reference counting
801 requirements\&.
802 .IP [1]
803 Starting from the \fBBasics\fR\&.
804 Edit the file "\fIexample\&.tcl\fR"\&.
805 Remove the definition of \fBhello\fR\&. Replace it with
806 .CS
807
808
809 critcl::cproc twice {double x} object0 {
810 return Tcl_NewDoubleObj(2*x);
811 }
812
813 .CE
814 .IP and rebuild the package\&.
815 .IP [2]
816 With \fBobject0\fR the translation layer assumes that the returned \fBTcl_Obj*\fR
817 value has a reference count of \fB0\fR\&. I\&.e\&. a value which is unowned and unshared\&.
818 .sp
819 This value is passed directly to Tcl for its use, without any changes\&. Tcl
820 increments the reference count and thus takes ownership\&. The value is still unshared\&.
821 .sp
822 It would be extremely detrimental if the translation layer had decremented the
823 reference count before passing the value\&. This action would release the memory and then
824 leave Tcl with a dangling pointer and the associated memory corruption bug to come\&.
825 .IP [3]
826 The situation changes when the C code returns a \fBTcl_Obj*\fR value with a
827 reference count greater than \fB0\fR\&. I\&.e\&. at least owned (by the C code), and possibly
828 even shared\&.
829 There are some object constructors and/or mutators in the public Tcl API which do that,
830 although I do not recall their names\&. The example below simulates this situation by
831 explicitly incrementing the reference count before returning the value\&.
832 .IP [4]
833 In this case use the type \fBobject\fR (without the trailing \fB0\fR)\&.
834 .IP [5]
835 Edit the file "\fIexample\&.tcl\fR" and replace the definition of \fBtwice\fR with
836 .CS
837
838
839 critcl::cproc twice {double x} object {
840 Tcl_Obj* result = Tcl_NewDoubleObj(2*x);
841 Tcl_IncrRefCount (result);
842 return result;
843 }
844
845 .CE
846 .IP and rebuild the package\&.
847 .IP [6]
848 After handing the value to Tcl, with the associated incremented reference count,
849 the translation layer decrements the reference count, invalidating the C code's ownership
850 and leaving the final reference count the same\&.
851 .sp
852 Note, the order matters\&. If the value has only one reference then decrementing it
853 before Tcl increments it would again release the value, and again leave Tcl with a
854 dangling pointer\&.
855 .sp
856 Also, not decrementing the reference count at all causes the inverse problem to the
857 memory corruption issues of before, memory leaks\&.
858 .IP [7]
859 \fINote\fR that both types transfer ownership of the value\&. Their difference is
860 just in the reference count of the value coming out of the function, and the (non-)actions
861 having to be (not) taken to effect said transfer without causing memory issues\&.
862 .PP
863 .SS "ERRORS & MESSAGES"
864 .IP [1]
865 Starting from the \fBBasics\fR\&.
866 Edit the file "\fIexample\&.tcl\fR"\&.
867 Remove the definition of \fBhello\fR\&. Replace it with
868 .CS
869
870
871 critcl::cproc sqrt {
872 Tcl_Interp* interp
873 double x
874 } object0 {
875 if (x < 0) {
876 Tcl_SetObjResult (interp, Tcl_ObjPrintf ("Expected double >=0, but got \\"%d\\"", x));
877 Tcl_SetErrorCode (interp, "EXAMPLE", "BAD", "DOMAIN", NULL);
878 return NULL;
879 }
880 return Tcl_NewDoubleObj(sqrt(x));
881 }
882
883 .CE
884 .IP and rebuild the package\&.
885 .IP [2]
886 In standard C-based packages commands signal errors by returning \fBTCL_ERROR\fR,
887 placing the error message as the interpreter result, and maybe providing an error code via
888 \fBTcl_SetErrorCode\fR\&.
889 .IP [3]
890 When using \fBcritcl::cproc\fR this is limited and hidden\&.
891 .IP [4]
892 The simple and string types for results do not allow failure\&. The value is returned
893 to the translation layer, converted into the interpreter result and then reported as
894 success (\fBTCL_OK\fR)\&.
895 .IP [5]
896 The object types on the other hand do allow for failure\&.
897 Return a \fBNULL\fR value to signal failure to the translation layer, which then reports
898 this to the interpreter via the standard \fBTCL_ERROR\fR\&.
899 .IP [6]
900 \fIAttention\fR Setting the desired error message and code into the interpreter is
901 still the responsibility of the function body\&.
902 .PP
903 .SS "TCL_INTERP* ACCESS"
904 .IP [1]
905 Reread the example in the \fBprevious\fR section\&.
906 .IP [2]
907 Note the type \fBTcl_Interp*\fR used for the first argument\&.
908 .IP [3]
909 This type is special\&.
910 .IP [4]
911 An argument of this type has to be the first argument of a function\&.
912 .IP [5]
913 Using it tells \fICriTcl\fR that the function needs access to the Tcl interpreter
914 calling it\&. It then arranges for that to happen in the generated C code\&.
915 .sp
916 Using functions from Tcl's public C API taking an interpreter argument in the
917 function body is a situation where this is needed\&.
918 .IP [6]
919 \fIThis special argument is not visible at the script level\fR\&.
920 .IP [7]
921 \fIThis special argument is not an argument of the Tcl command for the function\fR\&.
922 .IP [8]
923 In our example the \fBsqrt\fR command is called with a single argument\&.
924 .IP [9]
925 The name of the argument can be freely chosen\&. It is the type which is important
926 and triggers the special behaviour\&.
927 My prefered names are \fBip\fR and \fBinterp\fR\&.
928 .PP
929 .SS "BINARY DATA ARGUMENTS"
930 .IP [1]
931 Starting from the \fBBasics\fR\&.
932 Edit the file "\fIexample\&.tcl\fR"\&.
933 Remove the definition of \fBhello\fR\&. Replace it with
934 .CS
935
936
937 critcl::cproc hello {bytes x} void {
938 /* critcl_bytes x (\&.s, \&.len, \&.o); */
939 printf("hello world, with %d bytes \\n data: ", x\&.len);
940 for (i = 0; i < x\&.len; i++) {
941 printf(" %02x", x\&.s[i]);
942 if (i % 16 == 15) printf ("\\ndata: ");
943 }
944 if (i % 16 != 0) printf ("\\n");
945 }
946
947 .CE
948 .IP and rebuild the package\&.
949 .IP [2]
950 To deal with strings holding binary data use the type \fBbytes\fR\&. It ensures that
951 the function sees the proper binary data, and not how Tcl is encoding it internally, as
952 the string types would\&.
953 .PP
954 .SS "CONSTANT BINARY DATA RESULTS"
955 .IP [1]
956 Use the command \fBcritcl::cdata\fR to create a command taking no arguments and
957 returning a constant ByteArray value\&.
958 .sp
959 .CS
960
961
962 # P5 3 3 255 \\n \&.\&.\&.
963 critcl::cdata cross3x3pgm {
964 80 52 32 51 32 51 32 50 53 53 10
965 0 255 0
966 255 255 255
967 0 255 0
968 }
969
970 .CE
971 .PP
972 .SS "TCL RUNTIME VERSION"
973 .IP [1]
974 See and reread the \fBbasic package\fR for the introduction of the
975 commands referenced below\&.
976 .IP [2]
977 Use the command \fBcritcl::tcl\fR to tell \fICriTcl\fR the minimal version of Tcl
978 the package is to be used with\&.
979 .sp
980 This determines which Tcl headers all files are compiled against, and what version
981 of the public Tcl API is available to the C code\&.
982 .sp
983 Currently \fB8\&.4\fR, \fB8\&.5\fR and \fB8\&.6\fR are supported\&.
984 .sp
985 If not specified \fB8\&.4\fR is assumed\&.
986 .PP
987 .SS "ADDITIONAL TCL CODE"
988 .IP [1]
989 Starting from the \fBBasics\fR\&.
990 Edit the file "\fIexample\&.tcl\fR"\&.
991 Remove the definition of \fBhello\fR\&. Replace it with
992 .CS
993
994
995 critcl::cproc greetings::hello {} void {
996 printf("hello world\\n");
997 }
998
999 critcl::cproc greetings::hi {} void {
1000 printf("hi you\\n");
1001 }
1002
1003 .CE
1004 .IP and rebuild the package\&.
1005 .IP [2]
1006 The command \fBhello\fR is now available as \fBgreetings::hello\fR, and a second
1007 command \fBgreetings::hi\fR was added\&.
1008 .IP [3]
1009 Tcl has automatically created the namespace \fBgreetings\fR\&.
1010 .IP [4]
1011 Create a file "\fIexample-policy\&.tcl\fR" and enter
1012 .CS
1013
1014
1015 namespace eval greetings {
1016 namespace export hello hi
1017 namespace ensemble create
1018 }
1019
1020 .CE
1021 .IP into it\&.
1022 .IP [5]
1023 Edit "\fIexample\&.tcl\fR"\&. Add the code
1024 .CS
1025
1026
1027 critcl::tsources example-policy\&.tcl
1028
1029 .CE
1030 .IP and rebuild the package\&.
1031 .IP [6]
1032 The added Tcl code makes \fBgreetings\fR available as an \fIensemble\fR
1033 command\&.
1034 .sp
1035 The commands in the namespace have been registered as methods of the ensemble\&.
1036 .sp
1037 They can now be invoked as
1038 .CS
1039
1040
1041 greetings hello
1042 greetings hi
1043
1044 .CE
1045 .IP [7]
1046 The Tcl builtin command \fBstring\fR is an ensemble as well, as is \fBclock\fR\&.
1047 .PP
1048 .PP
1049 New commands: \fIcritcl::tsources\fR
1050 .SS "DEBUGGING SUPPORT"
1051 .IP [1]
1052 See and reread the \fBbasic package\fR for the introduction of the
1053 commands referenced below\&.
1054 .IP [2]
1055 Use the command \fBcritcl::debug\fR to activate various features supporting debugging\&.
1056 .sp
1057 .CS
1058
1059
1060 critcl::debug memory ;# Activate Tcl memory debugging (-DTCL_MEM_DEBUG)
1061 critcl::debug symbols ;# Activate building and linking with debugger symbols (-g)
1062 critcl::debug all ;# Shorthand for both `memory` and `symbols`\&.
1063
1064 .CE
1065 .PP
1066 .SS "INSTALL THE PACKAGE"
1067 .IP [1]
1068 Starting from the \fBBasics\fR\&.
1069 .IP [2]
1070 Use an interactive \fBtclsh\fR seesion to determine the value of
1071 \fBinfo library\fR\&.
1072 .sp
1073 For the purpose of this HowTo assume that this path is
1074 "\fI/home/aku/opt/ActiveTcl/lib/tcl8\&.6\fR"
1075 .IP [3]
1076 Invoke the critcl application in a terminal, using
1077 .CS
1078
1079
1080
1081 critcl -libdir /home/aku/opt/ActiveTcl/lib/tcl8\&.6 -pkg example\&.tcl
1082
1083
1084 .CE
1085 .IP [4]
1086 The package is now build and installed into the chosen directory\&.
1087 .CS
1088
1089
1090 % find /home/aku/opt/ActiveTcl/lib/tcl8\&.6/example/
1091 /home/aku/opt/ActiveTcl/lib/tcl8\&.6/example/
1092 /home/aku/opt/ActiveTcl/lib/tcl8\&.6/example/pkgIndex\&.tcl
1093 /home/aku/opt/ActiveTcl/lib/tcl8\&.6/example/critcl-rt\&.tcl
1094 /home/aku/opt/ActiveTcl/lib/tcl8\&.6/example/license\&.terms
1095 /home/aku/opt/ActiveTcl/lib/tcl8\&.6/example/linux-x86_64
1096 /home/aku/opt/ActiveTcl/lib/tcl8\&.6/example/linux-x86_64/example\&.so
1097 /home/aku/opt/ActiveTcl/lib/tcl8\&.6/example/teapot\&.txt
1098
1099 .CE
1100 .PP
1101 .SH "USING EXTERNAL LIBRARIES"
1102 To create a minimal package wrapping an external library
1103 .IP [1]
1104 Choose a directory to develop in and make it the working directory\&.
1105 This should not be a checkout of \fICriTcl\fR itself\&.
1106 .IP [2]
1107 Save the following example to a file\&. In the following it is assumed that the file
1108 was named "\fIexample\&.tcl\fR"\&.
1109 .CS
1110
1111
1112 # -*- tcl -*-
1113 # Critcl support, absolutely necessary\&.
1114 package require critcl
1115
1116 # Bail out early if the compile environment is not suitable\&.
1117 if {![critcl::compiling]} {
1118 error "Unable to build project, no proper compiler found\&."
1119 }
1120
1121 # Information for the teapot\&.txt meta data file put into a generated package\&.
1122 # Free form strings\&.
1123 critcl::license {Andreas Kupries} {Under a BSD license}
1124
1125 critcl::summary {The second CriTcl-based package}
1126
1127 critcl::description {
1128 This package is the second example of a CriTcl-based package\&. It contains all the
1129 necessary and conventionally useful pieces for wrapping an external library\&.
1130 }
1131
1132 critcl::subject {external library usage} example {critcl package}
1133 critcl::subject {wrapping external library}
1134
1135 # Minimal Tcl version the package should load into\&.
1136 critcl::tcl 8\&.6
1137
1138 # Locations for headers and shared library of the library to wrap\&.
1139 # Required only for non-standard locations, i\&.e\&. where CC is not searching by default\&.
1140 critcl::cheaders -I/usr/include
1141 critcl::clibraries -L/usr/lib/x86_64-linux-gnu
1142 critcl::clibraries -lzstd
1143
1144 # Import library API, i\&.e\&. headers\&.
1145 critcl::include zstd\&.h
1146
1147 # ## #### ######### ################ #########################
1148 ## (De)compression using Zstd
1149 ## Data to (de)compress is passed in and returned as Tcl byte arrays\&.
1150
1151 critcl::cproc compress {
1152 Tcl_Interp* ip
1153 bytes data
1154 int {level ZSTD_CLEVEL_DEFAULT}
1155 } object0 {
1156 /* critcl_bytes data; (\&.s, \&.len, \&.o) */
1157 Tcl_Obj* error_message;
1158
1159 int max = ZSTD_maxCLevel();
1160 if ((level < 1) || (level > max)) {
1161 error_message = Tcl_ObjPrintf ("level must be integer between 1 and %d", max);
1162 goto err;
1163 }
1164
1165 size_t dest_sz = ZSTD_compressBound (data\&.len);
1166 void* dest_buf = Tcl_Alloc(dest_sz);
1167
1168 if (!dest_buf) {
1169 error_message = Tcl_NewStringObj ("can't allocate memory to compress data", -1);
1170 goto err;
1171 }
1172
1173 size_t compressed_size = ZSTD_compress (dest_buf, dest_sz,
1174 data\&.s, data\&.len,
1175 level);
1176 if (ZSTD_isError (compressed_size)) {
1177 Tcl_Free(dest_buf);
1178 error_message = Tcl_ObjPrintf ("zstd encoding error: %s",
1179 ZSTD_getErrorName (compressed_size));
1180 goto err;
1181 }
1182
1183 Tcl_Obj* compressed = Tcl_NewByteArrayObj (dest_buf, compressed_size);
1184 Tcl_Free (dest_buf);
1185
1186 return compressed;
1187 err:
1188 Tcl_SetObjResult (ip, error_message);
1189 return 0;
1190 }
1191
1192 critcl::cproc decompress {
1193 Tcl_Interp* ip
1194 bytes data
1195 } object0 {
1196 Tcl_Obj* error_message;
1197
1198 size_t dest_sz = ZSTD_getDecompressedSize (data\&.s, data\&.len);
1199 if (dest_sz == 0) {
1200 error_message = Tcl_NewStringObj("invalid data", -1);
1201 goto err;
1202 }
1203
1204 void* dest_buf = Tcl_Alloc (dest_sz);
1205 if (!dest_buf) {
1206 error_message = Tcl_NewStringObj("failed to allocate decompression buffer", -1);
1207 goto err;
1208 }
1209
1210 size_t decompressed_size = ZSTD_decompress (dest_buf, dest_sz,
1211 data\&.s, data\&.len);
1212 if (decompressed_size != dest_sz) {
1213 Tcl_Free (dest_buf);
1214 error_message = Tcl_ObjPrintf("zstd decoding error: %s",
1215 ZSTD_getErrorName (decompressed_size));
1216 goto err;
1217 }
1218
1219 Tcl_Obj* decompressed = Tcl_NewByteArrayObj (dest_buf, dest_sz);
1220 Tcl_Free (dest_buf);
1221
1222 return decompressed;
1223
1224 err:
1225 Tcl_SetObjResult (ip, error_message);
1226 return 0;
1227 }
1228
1229 # ## #### ######### ################ #########################
1230
1231 # Forcing compilation, link, and loading now\&.
1232 critcl::msg -nonewline { Building \&.\&.\&.}
1233 if {![critcl::load]} {
1234 error "Building and loading the project failed\&."
1235 }
1236
1237 # Name and version the package\&. Just like for every kind of Tcl package\&.
1238 package provide critcl-example 1
1239
1240
1241 .CE
1242 .IP [3]
1243 Build the package\&. See the \fBBasics\fR, if necessary\&.
1244 .IP [4]
1245 Load the package and invoke the commands\&.
1246 .sp
1247 \fIAttention\fR\&. The commands take and return binary data\&.
1248 This may look very bad in the terminal\&.
1249 .IP [5]
1250 To test the commands enter
1251 .CS
1252
1253
1254 set a [compress {hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhello wwwwwwwworld}]
1255
1256 decompress $a
1257
1258 .CE
1259 .IP in the interactive \fBtclsh\fR
1260 .PP
1261 .PP
1262 New commands: \fIcritcl::cheaders\fR, \fIcritcl::clibraries\fR, \fIcritcl::include\fR\&.
1263 .SS "DEFAULT VALUES FOR ARGUMENTS"
1264 .IP [1]
1265 Reread the example of the main section\&. Note specifically the line
1266 .CS
1267
1268
1269 int {level ZSTD_CLEVEL_DEFAULT}
1270
1271 .CE
1272 .IP [2]
1273 This line demonstrates that \fBcritcl::cproc\fR arguments allowed to have default
1274 values, in the same vein as \fBproc\fR arguments, and using the same syntax\&.
1275 .IP [3]
1276 \fIAttention\fR Default values have to be legal C rvalues and match the C type of
1277 the argument\&.
1278 .sp
1279 They are literally pasted into the generated C code\&.
1280 .sp
1281 They bypass any argument validation done in the generated translation layer\&. This
1282 means that it is possible to use a value an invoker of the command cannot use from Tcl\&.
1283 .IP [4]
1284 This kind of in-band signaling of a default versus a regular argument is however
1285 not necessary\&.
1286 .sp
1287 Look at
1288 .CS
1289
1290
1291 critcl::cproc default_or_not {int {x 0}} void {
1292 if !has_x {
1293 printf("called with default\\n");
1294 return
1295 }
1296 printf("called with %d\\n", x);
1297 }
1298
1299 .CE
1300 .sp
1301 Any argument \fIx\fR with a default causes \fICriTcl\fR to create a hidden
1302 argument \fIhas_x\fR, of type int (boolean)\&.
1303 This argument is set to \fB1\fR when \fIx\fR was filled from defaults, and \fB0\fR
1304 else\&.
1305 .PP
1306 .SS "CUSTOM ARGUMENT VALIDATION"
1307 .IP [1]
1308 Starting from the \fBbase wrapper\fR\&.
1309 Edit the file "\fIexample\&.tcl\fR"\&. Replace the entire \fBcompress\fR function with
1310 .CS
1311
1312
1313 critcl::argtype zstd_compression_level {
1314 /* argtype: `int` */
1315 if (Tcl_GetIntFromObj (interp, @@, &@A) != TCL_OK) return TCL_ERROR;
1316 /* additional validation */
1317 int max = ZSTD_maxCLevel();
1318 if ((@A < 1) || (@A > max)) {
1319 Tcl_SetObjResult (interp,
1320 Tcl_ObjPrintf ("zstd compression level must be integer between 1 and %d", max));
1321 return TCL_ERROR;
1322 }
1323 /* @@: current objv[] element
1324 ** @A: name of argument variable for transfer to C function
1325 ** interp: predefined variable, access to current interp - error messages, etc\&.
1326 */
1327 } int int ;# C types of transfer variable and function argument\&.
1328
1329 critcl::cproc compress {
1330 Tcl_Interp* ip
1331 bytes data
1332 zstd_compression_level {level ZSTD_CLEVEL_DEFAULT}
1333 } object0 {
1334 /* critcl_bytes data; (\&.s, \&.len, \&.o) */
1335 /* int level; validated to be in range 1\&.\&.\&.ZSTD_maxCLevel() */
1336
1337 Tcl_Obj* error_message;
1338
1339 size_t dest_sz = ZSTD_compressBound (data\&.len);
1340 void* dest_buf = Tcl_Alloc(dest_sz);
1341
1342 if (!dest_buf) {
1343 error_message = Tcl_NewStringObj ("can't allocate memory to compress data", -1);
1344 goto err;
1345 }
1346
1347 size_t compressed_size = ZSTD_compress (dest_buf, dest_sz,
1348 data\&.s, data\&.len,
1349 level);
1350 if (ZSTD_isError (compressed_size)) {
1351 Tcl_Free(dest_buf);
1352 error_message = Tcl_ObjPrintf ("zstd encoding error: %s",
1353 ZSTD_getErrorName (compressed_size));
1354 goto err;
1355 }
1356
1357 Tcl_Obj* compressed = Tcl_NewByteArrayObj (dest_buf, compressed_size);
1358 Tcl_Free (dest_buf);
1359
1360 return compressed;
1361 err:
1362 Tcl_SetObjResult (ip, error_message);
1363 return 0;
1364 }
1365
1366 .CE
1367 .IP and rebuild the package\&.
1368 .sp
1369 In the original example the \fIlevel\fR argument of the function was validated in
1370 the function itself\&.
1371 This may detract from the funtionality of interest itself, especially if there are lots of
1372 arguments requiring validation\&.
1373 If the same kind of argument is used in multiple places this causes code duplication in
1374 the functions as well\&.
1375 .sp
1376 Use a custom argument type as defined by the modification to move this kind of
1377 validation out of the function, and enhance readability\&.
1378 .sp
1379 Code duplication however is only partially adressed\&.
1380 While there is no duplication in the visible definitions the C code of the new argument
1381 type is replicated for each use of the type\&.
1382 .IP [2]
1383 Now replace the \fBargtype\fR definition with
1384 .CS
1385
1386
1387 critcl::code {
1388 int GetCompressionLevel (Tcl_Interp* interp, Tcl_Obj* obj, int* level)
1389 {
1390 if (Tcl_GetIntFromObj (interp, obj, level) != TCL_OK) return TCL_ERROR;
1391
1392 int max = ZSTD_maxCLevel();
1393 if ((*level < 1) || (*level > max)) {
1394 Tcl_SetObjResult (interp,
1395 Tcl_ObjPrintf ("zstd compression level must be integer between 1 and %d", max));
1396 return TCL_ERROR;
1397 }
1398 return TCL_OK;
1399 }
1400 }
1401
1402 critcl::argtype zstd_compression_level {
1403 if (GetCompressionLevel (@@, &@A) != TCL_OK) return TCL_ERROR;
1404 } int int
1405
1406 .CE
1407 .IP and rebuild the package\&.
1408 .sp
1409 Now only the calls to the new validation function are replicated\&.
1410 The function itself exists only once\&.
1411 .PP
1412 .SS "SEPARATING LOCAL C SOURCES"
1413 .IP [1]
1414 Starting from the end of the \fBprevious\fR section\&.
1415 Edit the file "\fIexample\&.tcl\fR"\&.
1416 .IP [2]
1417 Save the contents of the \fBcritcl::ccode\fR block into a file "\fIexample\&.c\fR" and
1418 then replace the entire block with
1419 .CS
1420
1421
1422 critcl::csources example\&.c
1423
1424 critcl::ccode {
1425 extern int GetCompressionLevel (Tcl_Interp* interp, Tcl_Obj* obj, int* level);
1426 }
1427
1428 .CE
1429 .sp
1430 When mixing C and Tcl code the different kind of indentation rules for these
1431 languages may come into strong conflict\&. Further, very large blocks of C code may reduce
1432 overall readability\&.
1433 .IP [3]
1434 The examples fixes this by moving the code block into a local C file and then
1435 registering this file with \fICriTcl\fR\&.
1436 When building the package \fICriTcl\fR arranges to build all such registered C files as
1437 well\&.
1438 .IP [4]
1439 \fIAttention\fR\&. The C code is now in a separate compilation unit\&.
1440 The example declares the exported function so that the \fBcproc\fRs are again able to see
1441 and use it\&.
1442 .IP [5]
1443 Now go a step further\&. Save the declaration into a file "\fIexample\&.h\fR", and then
1444 use
1445 .CS
1446
1447
1448 critcl::include example\&.h
1449
1450 .CE
1451 .IP to import it\&. Note that this is just a shorthand for
1452 .CS
1453
1454 critcl::ccode {
1455 #include "example\&.h"
1456 }
1457
1458 .CE
1459 .IP [6]
1460 As an alternative solution, start from the beginning of the section and move the
1461 entire original \fBcritcl::ccode\fR block into a file "\fIexample-check\&.tcl\fR"\&.
1462 .sp
1463 Then replace it with
1464 .CS
1465
1466
1467 critcl::source example-check\&.tcl
1468
1469 .CE
1470 .IP to import it into the main code again\&.
1471 .sp
1472 \fIAttention\fR Tcl's builtin command \fBsource\fR is \fInot suitable\fR for
1473 importing the separate file due to how \fICriTcl\fR uses the information from
1474 \fBinfo script\fR to key various internal datastructures\&.
1475 .PP
1476 .SS "VERY SIMPLE RESULTS"
1477 .IP [1]
1478 Starting from the end of the \fBvalidation\fR section\&.
1479 Edit the file "\fIexample\&.tcl\fR"\&.
1480 Add the code below, just before the \fBcompress\fR command\&.
1481 .CS
1482
1483
1484 critcl::cconst version char* ZSTD_VERSION_STRING
1485 critcl::cconst min-level int 1
1486 critcl::cconst max-level int ZSTD_maxCLevel()
1487
1488 .CE
1489 .IP and rebuild the package\&.
1490 .IP [2]
1491 These declarations create three additional commands, each returning the specified
1492 value\&. A fixed string, an integer, and a function call returning an integer\&.
1493 .IP [3]
1494 \fIAttention\fR The values have to be legal C rvalues and match the C type of the
1495 result\&. They are literally pasted into the generated C code\&.
1496 .IP [4]
1497 When using \fBcritcl::cconst\fR \fICriTcl\fR is aware that the result of the
1498 function does not depend on any parameters and is computed in a single C expression\&.
1499 .sp
1500 This enables it do to away with the internal helper function it would need and
1501 generate if \fBcritcl::cproc\fR had been used instead\&.
1502 For example
1503 .CS
1504
1505
1506 critcl::cproc version {} char* {
1507 return ZSTD_VERSION_STRING;
1508 }
1509
1510 .CE
1511 .PP
1512 .SS "STRUCTURE ARGUMENTS"
1513 .IP [1]
1514 For all that this is a part of how to
1515 \fBUse External Libraries\fR, for the demonstratation
1516 only the basics are needed\&.
1517 .IP [2]
1518 Starting from the \fBBasics\fR\&.
1519 Edit the file "\fIexample\&.tcl\fR"\&.
1520 Remove the definition of \fBhello\fR\&. Replace it with
1521 .CS
1522
1523
1524 critcl::ccode {
1525 typedef struct vec2 {
1526 double x;
1527 double y;
1528 } vec2;
1529
1530 typedef vec2* vec2ptr;
1531
1532 int
1533 GetVecFromObj (Tcl_Interp* interp, Tcl_Obj* obj, vec2ptr* vec)
1534 {
1535 int len;
1536 if (Tcl_ListObjLength (interp, obj, &len) != TCL_OK) return TCL_ERROR;
1537 if (len != 2) {
1538 Tcl_SetObjResult (interp, Tcl_ObjPrintf ("Expected 2 elements, got %d", len));
1539 return TCL_ERROR;
1540 }
1541
1542 Tcl_Obj* lv[2];
1543 if (Tcl_ListObjGetElements (interp, obj, &lv) != TCL_OK) return TCL_ERROR;
1544
1545 double x, y;
1546 if (Tcl_GetDoubleFromObj (interp, lv[0], &x) != TCL_OK) return TCL_ERROR;
1547 if (Tcl_GetDoubleFromObj (interp, lv[1], &y) != TCL_OK) return TCL_ERROR;
1548
1549 *vec = Tcl_Alloc (sizeof (vec2));
1550 (*vec)->x = x;
1551 (*vec)->y = y;
1552 return TCL_OK;
1553 }
1554 }
1555
1556 critcl::argtype vec2 {
1557 if (GetVecFromObj (interp, @@, &@A) != TCL_OK) return TCL_ERROR;
1558 } vec2ptr vec2ptr
1559
1560 critcl::argtyperelease vec2 {
1561 /* @A : C variable holding the data to release */
1562 Tcl_Free ((char*) @A);
1563 }
1564
1565 critcl::cproc norm {vec2 vector} double {
1566 double norm = hypot (vector->x, vector->y);
1567 return norm;
1568 }
1569
1570 .CE
1571 .IP and rebuild the package\&.
1572 .IP [3]
1573 The structure to pass as argument is a 2-dimensional vector\&. It is actually passed
1574 in as a pointer to a \fBvec2\fR structure\&.
1575 This pointer is created by the \fBGetVecFromObj\fR function\&. It allocates and fills the
1576 structure from the Tcl value, which has to be a list of 2 doubles\&. The bulk of the code in
1577 \fBGetVecFromObj\fR is for verifying this and extracting the doubles\&.
1578 .IP [4]
1579 The \fBargtyperelease\fR code releases the pointer when the C function returns\&. In
1580 other words, the pointer to the structure is owned by the translation layer and exists
1581 only while the function is active\&.
1582 .IP [5]
1583 While working this code has two disadvantages\&.
1584 First there is memory churn\&. Each call of \fBnorm\fR causes the creation and release of a
1585 temporary \fBvec2\fR structure for the argument\&.
1586 Second is the need to always extract the data from the \fBTcl_Obj*\fR value\&.
1587 .sp
1588 Both can be done better\&.
1589 .sp
1590 We will come back to this after explaining how to return structures to Tcl\&.
1591 .PP
1592 .SS "STRUCTURE RESULTS"
1593 .IP [1]
1594 Starting from the end of the \fBprevious\fR section\&.
1595 .IP [2]
1596 Edit the file "\fIexample\&.tcl\fR" and add the following code, just after the
1597 definition of the \fBnorm\fR command\&.
1598 .CS
1599
1600
1601 critcl::resulttype vec2 {
1602 /* rv: result value of function, interp: current Tcl interpreter */
1603 if (rv == NULL) return TCL_ERROR;
1604 Tcl_Obj* lv[2];
1605 lv[0] = Tcl_NewDoubleObj (rv->x);
1606 lv[1] = Tcl_NewDoubleObj (rv->y);
1607 Tcl_SetObjResult (interp, Tcl_NewListObj (2, lv));
1608 Tcl_Free (rv);
1609 return TCL_OK;
1610 } vec2ptr ;# C result type
1611
1612 critcl::cproc add {vec2 a vec2 b} vec2 {
1613 vec2ptr z = Tcl_Alloc (sizeof (vec2));
1614
1615 z->x = a->x + b->x;
1616 z->y = a->y + b->y;
1617
1618 return z;
1619 }
1620
1621 .CE
1622 .IP and rebuild the package\&.
1623 .IP [3]
1624 The new command \fBadd\fR takes two vectors and return the element-wise sum of both
1625 as a new vector\&.
1626 .IP [4]
1627 The function allocates and initializes a structure and hands it over to the
1628 translation layer\&. Which in turn constructs a Tcl list of 2 doubles from it, sets that as
1629 the command's result and at last discards the allocated structure again\&.
1630 .IP [5]
1631 While working this code has two disadvantages\&.
1632 First there is memory churn\&. Each call of \fBadd\fR causes the creation and release of
1633 three temporary \fBvec2\fR structures\&. One per argument, and one for the result\&.
1634 Second is the need to always construct a complex \fBTcl_Obj*\fR value from the structure\&.
1635 .sp
1636 Both can be done better\&. This is explained in the next section\&.
1637 .PP
1638 .SS "STRUCTURE TYPES"
1639 .IP [1]
1640 Starting from the end of the previous section\&.
1641 .IP [2]
1642 Edit the file "\fIexample\&.tcl\fR"\&.
1643 .IP [3]
1644 Remove the entire functionality (type definitions, related C code, and cprocs)\&.
1645 Replace it with
1646 .CS
1647
1648
1649 critcl::ccode {
1650 typedef struct vec2 {
1651 double x;
1652 double y;
1653 } vec2;
1654
1655 typedef vec2* vec2ptr;
1656
1657 /* -- Core vector structure management -- */
1658
1659 static vec2ptr Vec2New (double x, double y) {
1660 vec2ptr vec = Tcl_Alloc (sizeof (vec2));
1661 vec->x = x;
1662 vec->y = y;
1663 return vec;
1664 }
1665
1666 static vec2ptr Vec2Copy (vec2ptr src) {
1667 vec2ptr vec = Tcl_Alloc (sizeof (vec2));
1668 *vec = *src
1669 return vec;
1670 }
1671
1672 static void Vec2Release (vec2ptr vec) {
1673 Tcl_Free ((char*) vec);
1674 }
1675
1676 /* -- Tcl value type for vec2 -- Tcl_ObjType -- */
1677
1678 static void Vec2Free (Tcl_Obj* obj);
1679 static void Vec2StringOf (Tcl_Obj* obj);
1680 static void Vec2Dup (Tcl_Obj* obj, Tcl_Obj* dst);
1681 static int Vec2FromAny (Tcl_Interp* interp, Tcl_Obj* obj);
1682
1683 Tcl_ObjType vec2_objtype = {
1684 "vec2",
1685 Vec2Free,
1686 Vec2Dup,
1687 Vec2StringOf,
1688 Vec2FromAny
1689 };
1690
1691 static void Vec2Free (Tcl_Obj* obj) {
1692 Vec2Release ((vec2ptr) obj->internalRep\&.otherValuePtr);
1693 }
1694
1695 static void Vec2Dup (Tcl_Obj* obj, Tcl_Obj* dst) {
1696 vec2ptr vec = (vec2ptr) obj->internalRep\&.otherValuePtr;
1697
1698 dst->internalRep\&.otherValuePtr = Vec2Copy (vec);
1699 dst->typePtr = &vec2_objtype;
1700 }
1701
1702 static void Vec2StringOf (Tcl_Obj* obj) {
1703 vec2ptr vec = (vec2ptr) obj->internalRep\&.otherValuePtr;
1704
1705 /* Serialize vector data to string (list of two doubles) */
1706 Tcl_DString ds;
1707 Tcl_DStringInit (&ds);
1708
1709 char buf [TCL_DOUBLE_SPACE];
1710
1711 Tcl_PrintDouble (0, vec->x, buf); Tcl_DStringAppendElement (&ds, buf);
1712 Tcl_PrintDouble (0, vec->y, buf); Tcl_DStringAppendElement (&ds, buf);
1713
1714 int length = Tcl_DStringLength (ds);
1715
1716 /* Set string representation */
1717 obj->length = length;
1718 obj->bytes = Tcl_Alloc(length+1);
1719 memcpy (obj->bytes, Tcl_DStringValue (ds), length);
1720 obj->bytes[length] = '\\0';
1721 /*
1722 ** : package require critcl::cutil ;# get C utilities
1723 ** : critcl::cutil::alloc ;# Activate allocation utilities
1724 ** : (Internally cheaders, include)
1725 ** : Then all of the above can be written as STREP_DS (obj, ds);
1726 ** : STREP_DS = STRing REP from DString
1727 */
1728
1729 Tcl_DStringFree (&ds);
1730 }
1731
1732 static int Vec2FromAny (Tcl_Interp* interp, Tcl_Obj* obj) {
1733 /* Change intrep of obj to vec2 structure\&.
1734 ** A Tcl list of 2 doubles is used as an intermediary intrep\&.
1735 */
1736
1737 int len;
1738 if (Tcl_ListObjLength (interp, obj, &len) != TCL_OK) return TCL_ERROR;
1739 if (len != 2) {
1740 Tcl_SetObjResult (interp, Tcl_ObjPrintf ("Expected 2 elements, got %d", len));
1741 return TCL_ERROR;
1742 }
1743
1744 Tcl_Obj* lv[2];
1745 if (Tcl_ListObjGetElements (interp, obj, &lv) != TCL_OK) return TCL_ERROR;
1746
1747 double x, y;
1748 if (Tcl_GetDoubleFromObj (interp, lv[0], &x) != TCL_OK) return TCL_ERROR;
1749 if (Tcl_GetDoubleFromObj (interp, lv[1], &y) != TCL_OK) return TCL_ERROR;
1750
1751 obj->internalRep\&.otherValuePtr = (void*) Vec2New (x, y);
1752 obj->typePtr = &vec2_objtype;
1753
1754 return TCL_OK;
1755 }
1756
1757 /* -- (un)packing structures from/into Tcl values -- */
1758
1759 int GetVecFromObj (Tcl_Interp* interp, Tcl_Obj* obj, vec2ptr* vec)
1760 {
1761 if (obj->typePtr != &vec2_objtype) {
1762 if (Vec2FromAny (interp, obj) != TCL_OK) return TCL_ERROR;
1763 }
1764
1765 *vec = (vec2ptr) obj->internalRep\&.otherValuePtr;
1766 return TCL_OK;
1767 }
1768
1769 Tcl_Obj* NewVecObj (vec2ptr vec) {
1770 Tcl_Obj* obj = Tcl_NewObj ();
1771
1772 Tcl_InvalidateStringRep (obj);
1773
1774 obj->internalRep\&.otherValuePtr = Vec2Copy (vec);
1775 obj->typePtr = &vec2_objtype;
1776
1777 return obj;
1778 }
1779 }
1780
1781 critcl::argtype vec2 {
1782 if (GetVecFromObj (interp, @@, &@A) != TCL_OK) return TCL_ERROR;
1783 } vec2ptr vec2ptr
1784
1785 critcl::resulttype vec2 {
1786 /* rv: result value of function, interp: current Tcl interpreter */
1787 Tcl_SetObjResult (interp, NewVecObj (&rv));
1788 return TCL_OK;
1789 } vec2
1790
1791 critcl::cproc norm {vec2 vector} double {
1792 double norm = hypot (vector->x, vector->y);
1793 return norm;
1794 }
1795
1796 critcl::cproc add {vec2 a vec2 b} vec2 {
1797 vec2 z;
1798
1799 z\&.x = a->x + b->x;
1800 z\&.y = a->y + b->y;
1801
1802 return z;
1803 }
1804
1805 .CE
1806 .IP and rebuild the package\&.
1807 .IP [4]
1808 This implements a new \fBTcl_ObjType\fR to handle \fBvec2\fR structures\&. With it
1809 \fBvec2\fR structures are become usable as internal representation (\fIintrep\fR of
1810 \fBTcl_Obj*\fR values\&.
1811 .sp
1812 The two functions \fBNewVecObj\fR and \fBGetVecFromObj\fR pack and unpack the
1813 structures from and into \fBTcl_Obj*\fR values\&.
1814 The latter performs the complex deserialization into a structure if and only if needed,
1815 i\&.e\&. when the \fBTclObj*\fR value has no intrep, or the intrep for a different type\&.
1816 This process of changing the intrep of a Tcl value is called \fIshimmering\fR\&.
1817 .sp
1818 Intreps cache the interpretation of \fBTcl_Obj*\fR values as a specific kind of
1819 type\&. Here \fBvec2\fR\&. This reduces conversion effort and memory churn, as intreps are
1820 kept by the Tcl interpreter as long as possible and needed\&.
1821 .IP [5]
1822 The arguments of \fBnorm\fR and \fBadd\fR are now converted once on entry, if not
1823 yet in the proper type, or not at all, if so\&.
1824 .IP [6]
1825 \fIAttention\fR\&. This example has the issue of passing result structures by value
1826 through the stack, and then packing a copy into a \fBTcl_Obj*\fR value\&.
1827 While this is no trouble for structures as small as \fBvec2\fR larger structures may pose
1828 a problem\&.
1829 .sp
1830 We will address this in the next section\&.
1831 .PP
1832 .PP
1833 Packages: \fIcritcl::cutil\fR
1834 .SS "LARGE STRUCTURES"
1835 .IP [1]
1836 Starting from the end of the previous section\&.
1837 .IP [2]
1838 Edit the file "\fIexample\&.tcl\fR"\&.
1839 .IP [3]
1840 Describing each individual change is too complex\&. The following is easier\&.
1841 .IP [4]
1842 Save the file, then replace the entire functionality with the following\&.
1843 .IP [5]
1844 After that use a \fBdiff\fR of your choice to compare the files and see the
1845 critical changes\&.
1846 .CS
1847
1848
1849 critcl::ccode {
1850 typedef struct vec2 {
1851 unsigned int rc;
1852 double x;
1853 double y;
1854 } vec2;
1855
1856 typedef vec2* vec2ptr;
1857
1858 /* -- Core vector structure management -- */
1859
1860 static vec2ptr Vec2New (double x, double y) {
1861 vec2ptr vec = Tcl_Alloc (sizeof (vec2));
1862 vec->rc = 0;
1863 vec->x = x;
1864 vec->y = y;
1865 return vec;
1866 }
1867
1868 static vec2ptr Vec2Copy (vec2ptr src) {
1869 scr->rc ++;
1870 return src;
1871 }
1872
1873 static void Vec2Release (vec2ptr vec) {
1874 if (vec->rc > 1) {
1875 vec->rc --;
1876 return;
1877 }
1878
1879 Tcl_Free ((char*) vec);
1880 }
1881
1882 /* -- Vector obj type -- */
1883
1884 static void Vec2Free (Tcl_Obj* obj);
1885 static void Vec2StringOf (Tcl_Obj* obj);
1886 static void Vec2Dup (Tcl_Obj* obj, Tcl_Obj* dst);
1887 static int Vec2FromAny (Tcl_Interp* interp, Tcl_Obj* obj);
1888
1889 Tcl_ObjType vec2_objtype = {
1890 "vec2",
1891 Vec2Free,
1892 Vec2Dup,
1893 Vec2StringOf,
1894 Vec2FromAny
1895 };
1896
1897 static void Vec2Free (Tcl_Obj* obj) {
1898 Vec2Release ((vec2ptr) obj->internalRep\&.otherValuePtr);
1899 }
1900
1901 static void Vec2Dup (Tcl_Obj* obj, Tcl_Obj* dst) {
1902 vec2ptr vec = (vec2ptr) obj->internalRep\&.otherValuePtr;
1903
1904 dst->internalRep\&.otherValuePtr = Vec2Copy (vec);
1905 dst->typePtr = &vec2_objtype;
1906 }
1907
1908 static void Vec2StringOf (Tcl_Obj* obj) {
1909 vec2ptr vec = (vec2ptr) obj->internalRep\&.otherValuePtr;
1910
1911 /* Serialize vector data to string (list of two doubles) */
1912 Tcl_DString ds;
1913 Tcl_DStringInit (&ds);
1914
1915 char buf [TCL_DOUBLE_SPACE];
1916
1917 Tcl_PrintDouble (0, vec->x, buf); Tcl_DStringAppendElement (&ds, buf);
1918 Tcl_PrintDouble (0, vec->y, buf); Tcl_DStringAppendElement (&ds, buf);
1919
1920 int length = Tcl_DStringLength (ds);
1921
1922 /* Set string representation */
1923 obj->length = length;
1924 obj->bytes = Tcl_Alloc(length+1);
1925 memcpy (obj->bytes, Tcl_DStringValue (ds), length);
1926 obj->bytes[length] = '\\0';
1927 /*
1928 ** : package require critcl::cutil ;# get C utilities
1929 ** : critcl::cutil::alloc ;# Activate allocation utilities
1930 ** : (Internally cheaders, include)
1931 ** : Then all of the above can be written as STREP_DS (obj, ds);
1932 ** : STREP_DS = STRing REP from DString
1933 */
1934
1935 Tcl_DStringFree (&ds);
1936 }
1937
1938 static int Vec2FromAny (Tcl_Interp* interp, Tcl_Obj* obj) {
1939 /* Change internal rep of obj to vector structure\&.
1940 ** A Tcl list of 2 doubles is used as intermediary int rep\&.
1941 */
1942
1943 int len;
1944 if (Tcl_ListObjLength (interp, obj, &len) != TCL_OK) return TCL_ERROR;
1945 if (len != 2) {
1946 Tcl_SetObjResult (interp, Tcl_ObjPrintf ("Expected 2 elements, got %d", len));
1947 return TCL_ERROR;
1948 }
1949
1950 Tcl_Obj* lv[2];
1951 if (Tcl_ListObjGetElements (interp, obj, &lv) != TCL_OK) return TCL_ERROR;
1952
1953 double x, y;
1954 if (Tcl_GetDoubleFromObj (interp, lv[0], &x) != TCL_OK) return TCL_ERROR;
1955 if (Tcl_GetDoubleFromObj (interp, lv[1], &y) != TCL_OK) return TCL_ERROR;
1956
1957 obj->internalRep\&.otherValuePtr = (void*) Vec2New (x, y);
1958 obj->typePtr = &vec2_objtype;
1959
1960 return TCL_OK;
1961 }
1962
1963 /* (un)packing structures from/into Tcl values -- */
1964
1965 int GetVecFromObj (Tcl_Interp* interp, Tcl_Obj* obj, vec2ptr* vec)
1966 {
1967 if (obj->typePtr != &vec2_objtype) {
1968 if (VecFromAny (interp, obj) != TCL_OK) return TCL_ERROR;
1969 }
1970
1971 *vec = (vec2ptr) obj->internalRep\&.otherValuePtr;
1972 return TCL_OK;
1973 }
1974
1975 Tcl_Obj* NewVecObj (vec2ptr vec) {
1976 Tcl_Obj* obj = Tcl_NewObj ();
1977
1978 Tcl_InvalidateStringRep (obj);
1979
1980 obj->internalRep\&.otherValuePtr = Vec2Copy (vec);
1981 obj->typePtr = &vec2_objtype;
1982
1983 return obj;
1984 }
1985 }
1986
1987 critcl::argtype vec2 {
1988 if (GetVecFromObj (interp, @@, &@A) != TCL_OK) return TCL_ERROR;
1989 } vec2ptr vec2ptr
1990
1991 critcl::resulttype vec2 {
1992 /* rv: result value of function, interp: current Tcl interpreter */
1993 Tcl_SetObjResult (interp, NewVecObj (rv));
1994 return TCL_OK;
1995 } vec2ptr
1996
1997 critcl::cproc norm {vec2 vector} double {
1998 double norm = hypot (vector->x, vector->y);
1999 return norm;
2000 }
2001
2002 critcl::cproc add {vec2 a vec2 b} vec2 {
2003 return Vec2New (a->x + b->x, a->y + b->y);
2004 }
2005
2006 .CE
2007 .IP [6]
2008 The \fBvec2\fR structure is now reference counted\&.
2009 .IP [7]
2010 The core management functions, i\&.e\&. \fBVec2New\fR, \fBVec2Copy\fR, and
2011 \fBVec2Release\fR are changed to maintain that reference count\&.
2012 Starting at \fB0\fR on creation, copies increment, and releases decrement\&.
2013 A structure is actually only freed when its reference count falls to \fB0\fR or below\&.
2014 .IP [8]
2015 \fBvec2\fR results are changed to pointers, easily passed back through the stack\&.
2016 The modified translation layer just wraps it into a \fBTcl_Obj*\fR value\&.
2017 .IP [9]
2018 \fIAttention\fR\&. Duplicating such a \fBTcl_Obj*\fR does not duplicate the
2019 referenced \fBvec2\fR structure anymore, just adds a reference\&.
2020 .IP [10]
2021 Regarding \fBdiff\fR commands, I know of two graphical diffs for Tcl/Tk,
2022 \fITkDiff\fR [https://tkdiff\&.sourceforge\&.io], and \fIEskil\fR [http://eskil\&.tcl\&.tk]\&.
2023 .PP
2024 .PP
2025 Packages: \fIcritcl::cutil\fR
2026 .SS "EXTERNAL STRUCTURES"
2027 .IP [1]
2028 Handle structures provided by external libraries using either
2029 \fBStructure Types\fR or \fBLarge Structures\fR as template\&.
2030 .IP [2]
2031 \fIAttention\fR\&. The choice is with the developer\&.
2032 .sp
2033 This is true even if the external structure is not reference counted by itself\&.
2034 .sp
2035 To reference count a structure \fBS\fR without such simply wrap \fBS\fR into a
2036 local structure which provides the reference count and has a field for \fBS\fR (pointer
2037 or value)\&.
2038 .IP [3]
2039 \fIAttention\fR Opaque external types, i\&.e\&. pointers to structures with hidden
2040 fields, can also be handled by the given templates\&.
2041 .PP
2042 .SS "EXTERNAL ENUMERATIONS"
2043 This section demonstrates how to convert from any kind of enumeration provided by an
2044 external library to Tcl strings, and the converse\&.
2045 .IP [1]
2046 For all that this is a part of how to
2047 \fBUse External Libraries\fR, for the demonstratation
2048 only the basics are needed\&.
2049 .IP [2]
2050 Starting from the \fBBasics\fR\&.
2051 Edit the file "\fIexample\&.tcl\fR"\&.
2052 Remove the definition of \fBhello\fR\&. Replace it with
2053 .CS
2054
2055
2056 package require critcl::emap
2057
2058 # no header included due to use of literal ints instead of symbolic names
2059
2060 critcl::emap::def yaml_sequence_style_t {
2061 any 0
2062 block 1
2063 flow 2
2064 }
2065
2066 # encode: style to int
2067 critcl::cproc encode {yaml_sequence_style_t style} int {
2068 return style;
2069 }
2070
2071 # decode: int to style
2072 critcl::cproc decode {int style} yaml_sequence_style_t {
2073 return style;
2074 }
2075
2076 .CE
2077 .IP and rebuild the package\&.
2078 .IP [3]
2079 The map converts between the Tcl level strings listed on the left side to the C
2080 values on the right side, and the reverse\&.
2081 .IP [4]
2082 It automatically generates \fBcritcl::argtype\fR and \fBcritcl::resulttype\fR
2083 definitions\&.
2084 .IP [5]
2085 \fIAttention\fR Like the default values for \fBcproc\fR arguments, and the results
2086 for \fBcconst\fR definitions the values on the right side have to be proper C
2087 rvalues\&. They have to match C type \fBint\fR\&.
2088 .sp
2089 In other words, it is perfectly ok to use the symbolic names provided by the header
2090 file of the external library\&.
2091 .sp
2092 \fIAttention\fR This however comes at a loss in efficiency\&. As \fICriTcl\fR then
2093 has no insight into the covered range of ints, gaps, etc\&. it has to perform a linear
2094 search when mapping from C to Tcl\&. When it knows the exact integer values it can use a
2095 table lookup instead\&.
2096 .sp
2097 \fIAttention\fR It also falls back to a search if a lookup table would contain more
2098 than 50 entries\&.
2099 .PP
2100 .PP
2101 Packages: \fIcritcl::emap\fR
2102 .SS "EXTERNAL BITSETS/BITMAPS/FLAGS"
2103 This section demonstrates how to convert from any kind of bit-mapped flags provided by an
2104 external library to lists of Tcl strings, and the converse\&.
2105 .IP [1]
2106 For all that this is a part of how to
2107 \fBUse External Libraries\fR, for the demonstratation
2108 only the basics are needed\&.
2109 .IP [2]
2110 Starting from the \fBBasics\fR\&.
2111 Edit the file "\fIexample\&.tcl\fR"\&.
2112 Remove the definition of \fBhello\fR\&. Replace it with
2113 .CS
2114
2115
2116 # http://man7\&.org/linux/man-pages/man7/inotify\&.7\&.html
2117
2118 package require critcl::bitmap
2119
2120 # critcl::cheaders - n/a, header is in system directories
2121 critcl::include sys/inotify\&.h
2122
2123 critcl::bitmap::def tcl_inotify_events {
2124 accessed IN_ACCESS
2125 all IN_ALL_EVENTS
2126 attribute IN_ATTRIB
2127 closed IN_CLOSE
2128 closed-nowrite IN_CLOSE_NOWRITE
2129 closed-write IN_CLOSE_WRITE
2130 created IN_CREATE
2131 deleted IN_DELETE
2132 deleted-self IN_DELETE_SELF
2133 dir-only IN_ONLYDIR
2134 dont-follow IN_DONT_FOLLOW
2135 modified IN_MODIFY
2136 move IN_MOVE
2137 moved-from IN_MOVED_FROM
2138 moved-self IN_MOVE_SELF
2139 moved-to IN_MOVED_TO
2140 oneshot IN_ONESHOT
2141 open IN_OPEN
2142 overflow IN_Q_OVERFLOW
2143 unmount IN_UNMOUNT
2144 } {
2145 all closed move oneshot
2146 }
2147
2148 # encode: flag set to int
2149 critcl::cproc encode {tcl_inotify_events e} int {
2150 return e;
2151 }
2152
2153 # decode: int to flag set
2154 critcl::cproc decode {int e} tcl_inotify_events {
2155 return e;
2156 }
2157
2158
2159 .CE
2160 .IP and rebuild the package\&.
2161 .IP [3]
2162 The map converts between lists of the Tcl level strings listed on the left side to
2163 the bit-union of the C values on the right side, and the reverse\&.
2164 .sp
2165 It is noted that the four strings \fBall\fR, \fBclosed\fR, \fBmove\fR, and
2166 \fBoneshot\fR cannot be converted from C flags to list of strings, only from list to
2167 bits\&.
2168 .IP [4]
2169 It automatically generates \fBcritcl::argtype\fR and \fBcritcl::resulttype\fR
2170 definitions\&.
2171 .IP [5]
2172 \fIAttention\fR Like the default values for \fBcproc\fR arguments, and the results
2173 for \fBcconst\fR definitions the values on the right side have to be proper C
2174 rvalues\&. They have to match C type \fBint\fR\&.
2175 .sp
2176 In other words, it is perfectly ok to use the symbolic names provided by the header
2177 file of the external library\&. As shown\&.
2178 .PP
2179 .PP
2180 Packages: \fIcritcl::bitmap\fR
2181 .SS "NON-STANDARD HEADER/LIBRARY LOCATIONS"
2182 .IP [1]
2183 See and reread the \fBbasic wrapper package\fR for
2184 the introduction of the commands referenced below\&.
2185 .IP [2]
2186 \fIAttention\fR Relative paths will be resolved relative to the location of the
2187 "\fI\&.tcl\fR" file containing the \fICriTcl\fR commands\&.
2188 .IP [3]
2189 Use the command \fBcritcl::cheaders\fR to tell \fICriTcl\fR about non-standard
2190 locations for header files\&.
2191 .sp
2192 Multiple arguments are allowed, and multiple calls as well\&. The information
2193 accumulates\&.
2194 .sp
2195 Arguments of the form "\fI-Idirectory\fR" register the directory directly\&.
2196 .sp
2197 For arguments of the form "\fIpath\fR" the directory holding the path is
2198 registered\&. In other words, it is assumed to be the full path of a header \fIfile\fR, and
2199 not a directory\&.
2200 .sp
2201 .CS
2202
2203
2204 critcl::cheaders -I/usr/local/include
2205 critcl::cheaders local/types\&.h
2206 critcl::cheaders other-support/*\&.h
2207
2208 .CE
2209 .IP [4]
2210 Use the command \fBcritcl::include\fR to actually use a specific header file\&.
2211 .IP [5]
2212 Use the command \fBcritcl::clibraries\fR to tell \fICriTcl\fR about non-standard
2213 locations for shared libaries, and about shared libaries to link to
2214 .sp
2215 Multiple arguments are allowed, and multiple calls as well\&. The information
2216 accumulates\&.
2217 .sp
2218 Arguments of the form "\fI-Ldirectory\fR" register a directory\&.
2219 .sp
2220 Arguments of the form "\fI-lname\fR" register a shared libary to link to by
2221 name\&. The library will be looked for in both standard and registered directories\&.
2222 .sp
2223 Arguments of the form "\fI-path\fR" register a shared libary to link to by full
2224 path\&.
2225 .sp
2226 .CS
2227
2228
2229 critcl::clibraries -L/usr/lib/x86_64-linux-gnu
2230 critcl::clibraries -lzstd
2231 critcl::clibraries /usr/lib/x86_64-linux-gnu/libzstd\&.so
2232
2233 .CE
2234 .IP [6]
2235 On Mac OS X use the command \fBcritcl::framework\fR to name the frameworks to use
2236 in the package\&.
2237 .sp
2238 \fIAttention\fR Using the command on other platforms is ok, and will be ignored\&.
2239 .IP [7]
2240 Not answered in the above is how to find the necessary paths if they are not fixed
2241 across machines or platforms\&.
2242 .sp
2243 We will come back to this\&.
2244 .PP
2245 .SS "NON-STANDARD COMPILE/LINK CONFIGURATION"
2246 .IP [1]
2247 See and reread the \fBbasic wrapper package\fR for
2248 the introduction of the commands referenced below\&.
2249 .IP [2]
2250 Use the command \fBcritcl::cflags\fR to provide additional, non-standard flags to
2251 the compiler\&.
2252 .sp
2253 .CS
2254
2255
2256 critcl::cflags -DBYTE_ORDER=bigendian
2257
2258 .CE
2259 .IP [3]
2260 Use the command \fBcritcl::ldflags\fR to provide additional, non-standard flags to
2261 the linker\&.
2262 .sp
2263 .CS
2264
2265
2266 critcl::ldflags -
2267
2268 .CE
2269 .IP [4]
2270 Not answered in the above is how to determine such flags if they are not fixed
2271 across machines or platforms\&.
2272 .sp
2273 This is addressed by the next section\&.
2274 .PP
2275 .SS "QUERYING THE COMPILATION ENVIRONMENT"
2276 .IP [1]
2277 Use the command \fBcritcl::check\fR to immediately check if a piece of C code can
2278 compiled successfully as a means of querying the compiler configuration itself\&.
2279 .sp
2280 .CS
2281
2282
2283 if {[critcl::check {
2284 #include <FOO\&.h>
2285 }]} {
2286 Do stuff with FOO\&.h present\&.
2287 } else {
2288 Do stuff without FOO\&.h
2289 }
2290
2291 .CE
2292 .sp
2293 All header and library paths which were registered with \fICriTcl\fR before using
2294 \fBcritcl::check\fR take part in the attempted compilation\&.
2295 .sp
2296 Use the package \fBcritcl::util\fR and various convenience commands it
2297 provides\&.
2298 .IP [2]
2299 Use the full \fIPower of Tcl (tm)\fR itself\&.
2300 .PP
2301 .SS "SHARED C CODE"
2302 .IP [1]
2303 See and reread the \fBbasic wrapper package\fR for
2304 the introduction of the commands referenced below\&.
2305 .IP [2]
2306 Use the command \fBcritcl::ccode\fR to write C code residing outside of \fBcproc\fR
2307 bodies\&.
2308 .IP [3]
2309 Or, alternatively, place the C code into one or more "\fI\&.c\fR" files and use the
2310 command \fBcritcl::csources\fR to register them with \fICriTcl\fR for compilation\&.
2311 .IP [4]
2312 This topic is also treated in section \fBSeparating Local C Sources\fR\&.
2313 .PP
2314 .SH VARIOUS
2315 .SS "AUTHOR, LICENSE, DESCRIPTION, KEYWORDS"
2316 .IP [1]
2317 See and reread the \fBbasic package\fR for the introduction of the
2318 commands referenced below\&.
2319 .IP [2]
2320 Use the command \fBcritcl::license\fR to set the package license\&.
2321 .sp
2322 Use the same command to set the package author\&.
2323 .sp
2324 Both arguments are free form text\&.
2325 .IP [3]
2326 Use the command \fBcritcl::summary\fR to set a short package description\&.
2327 .IP [4]
2328 Use the command \fBcritcl::description\fR to set a longer package description\&.
2329 .sp
2330 The arguments of both commands are free form text\&.
2331 .IP [5]
2332 Use the command \fBcritcl::subject\fR to set one or more keywords\&.
2333 .sp
2334 \fIAttention\fR Contrary to the other commands the arguments accumulate\&.
2335 .IP [6]
2336 All the commands are optional\&.
2337 .IP [7]
2338 Their information is not placed into the generated C code\&.
2339 .IP [8]
2340 In \fIpackage mode\fR the information is placed into the file "\fIteapot\&.txt\fR"
2341 of the generated package\&.
2342 .IP [9]
2343 This file serves as integration point for \fITeapot\fR, the package system of
2344 \fIActiveTcl\fR\&.
2345 .PP
2346 .SS "GET CRITCL APPLICATION HELP"
2347 .IP [1]
2348 Invoke the command
2349 .CS
2350
2351
2352 critcl -help
2353
2354 .CE
2355 .IP in a terminal to get help about the \fBcritcl\fR application\&.
2356 .PP
2357 .SS "SUPPORTED TARGETS & CONFIGURATIONS"
2358 .IP [1]
2359 Invoke the application as
2360 .CS
2361
2362
2363 critcl -show
2364
2365 .CE
2366 .IP in a terminal to get the detailed configuration of the target for the current platform\&.
2367 .IP [2]
2368 Invoke the application as
2369 .CS
2370
2371
2372 critcl -show -target NAME
2373
2374 .CE
2375 .IP in a terminal to get the detailed configuration of the named target\&.
2376 .IP [3]
2377 Invoke the application as
2378 .CS
2379
2380
2381 critcl -targets
2382
2383 .CE
2384 .IP in a terminal to get a list of the available targets\&.
2385 .PP
2386 .SS "BUILDING A PACKAGE"
2387 .IP [1]
2388 Start at section \fBBasics\fR\&.
2389 .PP
2390 .SS "BUILDING A PACKAGE FOR DEBUGGING"
2391 .IP [1]
2392 Start at section \fBBasics\fR\&.
2393 .PP
2394 .SH AUTHORS
2395 Jean Claude Wippler, Steve Landers, Andreas Kupries
2396 .SH "BUGS, IDEAS, FEEDBACK"
2397 This document, and the package it describes, will undoubtedly contain
2398 bugs and other problems\&.
2399 Please report them at \fIhttps://github\&.com/andreas-kupries/critcl/issues\fR\&.
2400 Ideas for enhancements you may have for either package, application,
2401 and/or the documentation are also very welcome and should be reported
2402 at \fIhttps://github\&.com/andreas-kupries/critcl/issues\fR as well\&.
2403 .SH KEYWORDS
2404 C code, Embedded C Code, calling C code from Tcl, code generator, compile & run, compiler, dynamic code generation, dynamic compilation, generate package, linker, on demand compilation, on-the-fly compilation
2405 .SH CATEGORY
2406 Glueing/Embedded C code
2407 .SH COPYRIGHT
2408 .nf
2409 Copyright (c) Jean-Claude Wippler
2410 Copyright (c) Steve Landers
2411 Copyright (c) 2011-2024 Andreas Kupries
2412
2413 .fi