-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclbind-doc.html
1342 lines (1202 loc) · 51.3 KB
/
clbind-doc.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
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<!-- 2025-01-24 Fri 10:55 -->
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Exposing C++ Libraries with clbind</title>
<meta name="author" content="Alex Wood" />
<meta name="generator" content="Org Mode" />
<style>
#content { max-width: 60em; margin: auto; }
.title { text-align: center;
margin-bottom: .2em; }
.subtitle { text-align: center;
font-size: medium;
font-weight: bold;
margin-top:0; }
.todo { font-family: monospace; color: red; }
.done { font-family: monospace; color: green; }
.priority { font-family: monospace; color: orange; }
.tag { background-color: #eee; font-family: monospace;
padding: 2px; font-size: 80%; font-weight: normal; }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
.underline { text-decoration: underline; }
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
p.verse { margin-left: 3%; }
pre {
border: 1px solid #e6e6e6;
border-radius: 3px;
background-color: #f2f2f2;
padding: 8pt;
font-family: monospace;
overflow: auto;
margin: 1.2em;
}
pre.src {
position: relative;
overflow: auto;
}
pre.src:before {
display: none;
position: absolute;
top: -8px;
right: 12px;
padding: 3px;
color: #555;
background-color: #f2f2f299;
}
pre.src:hover:before { display: inline; margin-top: 14px;}
/* Languages per Org manual */
pre.src-asymptote:before { content: 'Asymptote'; }
pre.src-awk:before { content: 'Awk'; }
pre.src-authinfo::before { content: 'Authinfo'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
pre.src-ditaa:before { content: 'ditaa'; }
pre.src-dot:before { content: 'Graphviz'; }
pre.src-calc:before { content: 'Emacs Calc'; }
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
pre.src-fortran:before { content: 'Fortran'; }
pre.src-gnuplot:before { content: 'gnuplot'; }
pre.src-haskell:before { content: 'Haskell'; }
pre.src-hledger:before { content: 'hledger'; }
pre.src-java:before { content: 'Java'; }
pre.src-js:before { content: 'Javascript'; }
pre.src-latex:before { content: 'LaTeX'; }
pre.src-ledger:before { content: 'Ledger'; }
pre.src-lisp:before { content: 'Lisp'; }
pre.src-lilypond:before { content: 'Lilypond'; }
pre.src-lua:before { content: 'Lua'; }
pre.src-matlab:before { content: 'MATLAB'; }
pre.src-mscgen:before { content: 'Mscgen'; }
pre.src-ocaml:before { content: 'Objective Caml'; }
pre.src-octave:before { content: 'Octave'; }
pre.src-org:before { content: 'Org mode'; }
pre.src-oz:before { content: 'OZ'; }
pre.src-plantuml:before { content: 'Plantuml'; }
pre.src-processing:before { content: 'Processing.js'; }
pre.src-python:before { content: 'Python'; }
pre.src-R:before { content: 'R'; }
pre.src-ruby:before { content: 'Ruby'; }
pre.src-sass:before { content: 'Sass'; }
pre.src-scheme:before { content: 'Scheme'; }
pre.src-screen:before { content: 'Gnu Screen'; }
pre.src-sed:before { content: 'Sed'; }
pre.src-sh:before { content: 'shell'; }
pre.src-sql:before { content: 'SQL'; }
pre.src-sqlite:before { content: 'SQLite'; }
/* additional languages in org.el's org-babel-load-languages alist */
pre.src-forth:before { content: 'Forth'; }
pre.src-io:before { content: 'IO'; }
pre.src-J:before { content: 'J'; }
pre.src-makefile:before { content: 'Makefile'; }
pre.src-maxima:before { content: 'Maxima'; }
pre.src-perl:before { content: 'Perl'; }
pre.src-picolisp:before { content: 'Pico Lisp'; }
pre.src-scala:before { content: 'Scala'; }
pre.src-shell:before { content: 'Shell Script'; }
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
/* additional language identifiers per "defun org-babel-execute"
in ob-*.el */
pre.src-cpp:before { content: 'C++'; }
pre.src-abc:before { content: 'ABC'; }
pre.src-coq:before { content: 'Coq'; }
pre.src-groovy:before { content: 'Groovy'; }
/* additional language identifiers from org-babel-shell-names in
ob-shell.el: ob-shell is the only babel language using a lambda to put
the execution function name together. */
pre.src-bash:before { content: 'bash'; }
pre.src-csh:before { content: 'csh'; }
pre.src-ash:before { content: 'ash'; }
pre.src-dash:before { content: 'dash'; }
pre.src-ksh:before { content: 'ksh'; }
pre.src-mksh:before { content: 'mksh'; }
pre.src-posh:before { content: 'posh'; }
/* Additional Emacs modes also supported by the LaTeX listings package */
pre.src-ada:before { content: 'Ada'; }
pre.src-asm:before { content: 'Assembler'; }
pre.src-caml:before { content: 'Caml'; }
pre.src-delphi:before { content: 'Delphi'; }
pre.src-html:before { content: 'HTML'; }
pre.src-idl:before { content: 'IDL'; }
pre.src-mercury:before { content: 'Mercury'; }
pre.src-metapost:before { content: 'MetaPost'; }
pre.src-modula-2:before { content: 'Modula-2'; }
pre.src-pascal:before { content: 'Pascal'; }
pre.src-ps:before { content: 'PostScript'; }
pre.src-prolog:before { content: 'Prolog'; }
pre.src-simula:before { content: 'Simula'; }
pre.src-tcl:before { content: 'tcl'; }
pre.src-tex:before { content: 'TeX'; }
pre.src-plain-tex:before { content: 'Plain TeX'; }
pre.src-verilog:before { content: 'Verilog'; }
pre.src-vhdl:before { content: 'VHDL'; }
pre.src-xml:before { content: 'XML'; }
pre.src-nxml:before { content: 'XML'; }
/* add a generic configuration mode; LaTeX export needs an additional
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
pre.src-conf:before { content: 'Configuration File'; }
table { border-collapse:collapse; }
caption.t-above { caption-side: top; }
caption.t-bottom { caption-side: bottom; }
td, th { vertical-align:top; }
th.org-right { text-align: center; }
th.org-left { text-align: center; }
th.org-center { text-align: center; }
td.org-right { text-align: right; }
td.org-left { text-align: left; }
td.org-center { text-align: center; }
dt { font-weight: bold; }
.footpara { display: inline; }
.footdef { margin-bottom: 1em; }
.figure { padding: 1em; }
.figure p { text-align: center; }
.equation-container {
display: table;
text-align: center;
width: 100%;
}
.equation {
vertical-align: middle;
}
.equation-label {
display: table-cell;
text-align: right;
vertical-align: middle;
}
.inlinetask {
padding: 10px;
border: 2px solid gray;
margin: 10px;
background: #ffffcc;
}
#org-div-home-and-up
{ text-align: right; font-size: 70%; white-space: nowrap; }
textarea { overflow-x: auto; }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00; }
.org-info-js_info-navigation { border-style: none; }
#org-info-js_console-label
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
.org-info-js_search-highlight
{ background-color: #ffff00; color: #000000; font-weight: bold; }
.org-svg { }
</style>
<link rel="stylesheet" type="text/css" href="styles/readtheorg/css/htmlize.css"/><link rel="stylesheet" type="text/css" href="styles/readtheorg/css/readtheorg.css"/><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script><script type="text/javascript" src="styles/lib/js/jquery.stickytableheaders.min.js"></script><script type="text/javascript" src="styles/readtheorg/js/readtheorg.js"></script>
</head>
<body>
<div id="preamble" class="status">
<div id="top-menu">
<ul>
<li><a href="index.html">Clasp</a>
<ul>
<li><a href="news.html">News</a></li>
<li><a href="download.html">Download</a></li>
</ul></li>
<li><a href="index.html">Doc</a>
<ul>
<li><a href="license.html">License</a></li>
<li><a href="manual.html">Manual</a></li>
<li><a href="building.html">Building</a></li>
<li><a href="clbind-doc.html">Exposing C++ Libraries</a></li>
</ul></li>
<li><a href="index.html">Misc</a>
<ul>
<li><a href="community.html">Community</a></li>
<li><a href="projects.html">Projects</a></li>
<li><a href="media.html">Media</a></li>
<li><a href="acknowlegements.html">Acknowledgements</a></li>
</ul></li>
</ul>
</div>
</div>
<div id="content" class="content">
<h1 class="title">Exposing C++ Libraries with clbind</h1>
<div id="table-of-contents" role="doc-toc">
<h2>Table of Contents</h2>
<div id="text-table-of-contents" role="doc-toc">
<ul>
<li><a href="#orgd23b560">1. General information</a></li>
<li><a href="#org0048718">2. Defining bindings</a></li>
<li><a href="#orgfe9b330">3. Exposing Functions</a>
<ul>
<li><a href="#org9128413">3.1. Overloaded Functions</a></li>
</ul>
</li>
<li><a href="#org50cf406">4. Exposing Classes</a>
<ul>
<li><a href="#org489072c">4.1. Inheritance</a></li>
<li><a href="#org5401a4e">4.2. Constructors</a></li>
<li><a href="#orgf1d88c8">4.3. Member Functions</a></li>
<li><a href="#org82565d9">4.4. Static Member Function</a></li>
<li><a href="#orgc515c5d">4.5. Public Member Variables</a></li>
<li><a href="#org34ba3e9">4.6. Derivable classes</a></li>
</ul>
</li>
<li><a href="#org2e18ff8">5. Exposing Enums</a></li>
<li><a href="#org4f9e726">6. Translators</a>
<ul>
<li><a href="#orgb3ca3e4">6.1. Translation from C++ objects to Common Lisp objects</a></li>
<li><a href="#org50ed06f">6.2. Translation from Common Lisp objects to C++ objects</a>
<ul>
<li><a href="#orge14f3b2">6.2.1. Advanced from_object translators</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#org5880dea">7. Policies</a>
<ul>
<li><a href="#org2147839">7.1. pureOutValue<N></a></li>
<li><a href="#orgfe36ee6">7.2. outValue<N></a></li>
<li><a href="#orgffb2dba">7.3. adopt<n></a></li>
<li><a href="#org8af2a34">7.4. LambdaList</a></li>
<li><a href="#org78438e8">7.5. DocString</a></li>
</ul>
</li>
<li><a href="#org6d0a485">8. Lispification</a>
<ul>
<li><a href="#org78e956b">8.1. Camel case</a></li>
<li><a href="#orgece7402">8.2. Underscores become hyphens</a></li>
</ul>
</li>
<li><a href="#orgfa2d68b">9. Building</a></li>
</ul>
</div>
</div>
<div id="outline-container-orgd23b560" class="outline-2">
<h2 id="orgd23b560"><span class="section-number-2">1.</span> General information</h2>
<div class="outline-text-2" id="text-1">
<p>
clbind is based on luabind with some ideas borrowed from pybind11 and boost::python.
</p>
<p>
In order to expose C++ code to Lisp, you will need to write a bridge file, which is a C++
source file. This file uses the Clasp extension API to describe to Clasp exactly what of
your system should be exposed, and how.
</p>
</div>
</div>
<div id="outline-container-org0048718" class="outline-2">
<h2 id="org0048718"><span class="section-number-2">2.</span> Defining bindings</h2>
<div class="outline-text-2" id="text-2">
<p>
Clasp is able to load C++ libraries and expose functions, classes, methods and enums to Clasp Common Lisp.
Clasp needs a function that it can call at startup to expose these library members. This
function will be present in your bridge file, along with several other markers used to
inform Clasp of the nature of your library.
</p>
<p>
The <code>CL_EXPOSE</code> preprocessor macro is used to mark the startup function.
Within the startup function, packages can be declared. Functions, classes, methods and enums
can be added to packages, and they will then automatically be available within Clasp.
</p>
<p>
Here is an example of a simple bridge file. The code for this and further examples is
available <a href="https://github.com/clasp-developers/demo-clasp-cxx-interoperation/">on GitHub</a>.
</p>
<div class="org-src-container">
<pre class="src src-C++">#include <clasp/clasp.h> // (1)
void helloWorld() {
printf("Hello World\nThis is C++ code being invoked from Clasp Common Lisp\n");
}
PACKAGE_USE("COMMON-LISP");
PACKAGE_NICKNAME("HW");
NAMESPACE_PACKAGE_ASSOCIATION(hw,HWPkg,"HELLO-WORLD"); // (2)
namespace hw { // (3)
CL_EXPOSE // (4)
void hello_world_startup () { // (5)
using namespace clbind; // (6)
package_ sc(HWPkg); // (7)
sc.def("hello-world", &helloWorld, // (8)
"The classic! Print Hello world"_docstring);
}
</pre>
</div>
<ol class="org-ol">
<li>This header makes the exposure API available.</li>
<li>These three lines define a Lisp package named <code>HELLO-WORLD</code>, with nickname <code>HW</code>, which uses the standard <code>COMMON-LISP</code> package.
The <code>HELLO-WORLD</code> package is defined to correspond to the C++ namespace <code>hw</code>, and <code>HWPkg</code>
is defined to refer to this package from within C++, for subsequent definitions.</li>
<li>To avoid symbol clashes in C++, we recommend putting your code in a unique C++ namespace.</li>
<li>The <code>CL_EXPOSE</code> preprocessor macro is used to identify the startup function. This
function will be run when Clasp starts up to define the package.</li>
<li>The name of the function is arbitrary.</li>
<li>For convenience we use the clbind namespace, but you can use explicit prefixes if you like.</li>
<li>Binds the <code>sc</code> local variable to the Lisp package defined earlier.</li>
<li>Exposes the C++ function <code>helloWorld</code> to Lisp as <code>hello-world:hello-world</code>, and
supplies a docstring.</li>
</ol>
<p>
After <a href="#orgfa2d68b">building Clasp with this extension</a> it can be accessed from within Lisp.
</p>
<div class="org-src-container">
<pre class="src src-Lisp">COMMON-LISP-USER> (hw:hello-world)
Hello World
This is C++ code being invoked from Clasp Common Lisp
COMMON-LISP-USER>
</pre>
</div>
</div>
</div>
<div id="outline-container-orgfe9b330" class="outline-2">
<h2 id="orgfe9b330"><span class="section-number-2">3.</span> Exposing Functions</h2>
<div class="outline-text-2" id="text-3">
<p>
Exposing functions is done via the function <code>def</code>:
</p>
<div class="org-src-container">
<pre class="src src-C++">template <typename F, class... Policies>
scope def(char const* name,
F f,
Policies... policies )
</pre>
</div>
<p>
In this function
</p>
<dl class="org-dl">
<dt>name</dt><dd>is the name that the function will have in clasp. It is automatically <a href="#org6d0a485">lispified</a>,
i.e. a name with camel-casing is converted to a downcase name with dashes in between.
Using this automatic lispification is optional; see the Lispification section for details.</dd>
<dt>f</dt><dd>a pointer to the C++ function.</dd>
<dt>policies</dt><dd>Gives additional information (see <a href="#org5880dea">Policies</a>).</dd>
</dl>
<p>
For example, suppose we have a C++ function
</p>
<div class="org-src-container">
<pre class="src src-C++">double addThreeNumbers(double x, double y, double z) {
return x + y + z;
}
</pre>
</div>
<p>
and we want to expose this to Lisp, but with only one required parameter, the others
being optional and defaulting to zero. We could do that like so:
</p>
<div class="org-src-container">
<pre class="src src-C++">PACKAGE_NICKNAME("HW");
NAMESPACE_PACKAGE_ASSOCIATION(hw,HWPkg,"HELLO-WORLD");
namespace hw {
CL_EXPOSE
void hello_world_startup() {
using namespace clbind;
package_ sc(HWPkg);
sc.def("hello-world",&helloWorld,
"The classic! Print \"Hello World\""_docstring);
sc.def("addThreeNumbers",&addThreeNumbers, // (1)
"(x cl:&optional (y 0.0) (z 0.0))"_ll, // (2)
"Add three numbers and return the result"_docstring); // (3)
</pre>
</div>
<ol class="org-ol">
<li>Only the first two arguments to <code>def</code> are required: the name of the function
and a pointer to it.</li>
<li>The lambda list for the function is provided as a policy, using the <code>_ll</code> user literal
described below in <a href="#org8af2a34">LambdaList</a>.</li>
<li>A documentation string is provided with the <code>_docstring</code> user literal.</li>
</ol>
<p>
From Clasp, this function can be called with
<code>(hw:add-three-numbers 1)</code>, <code>(hw:add-three-numbers 1 2)</code>, or <code>(hw:add-three-numbers 1 2 3)</code>.
clbind performs automatic conversions, similar to C++, in order to translate Lisp numbers
of different types into C++ numbers.
The corresponding C++ calls would be <code>addThreeNumbers(1,0,0)</code>, <code>addThreeNumbers(1,2,0)</code>,
and <code>addThreeNumbers(1,2,3)</code>, respectively.
</p>
<p>
The lambda list and documentation string can be seen using the Common Lisp function <code>describe</code>:
</p>
<div class="org-src-container">
<pre class="src src-lisp">COMMON-LISP-USER> (describe 'hw:add-three-numbers)
HELLO-WORLD:ADD-THREE-NUMBERS - external symbol in HELLO-WORLD package
-----------------------------------------------------------------------------
HELLO-WORLD:ADD-THREE-NUMBERS [Function]
Documentation: "Add three numbers and return the result"
Arguments: (HELLO-WORLD::X &OPTIONAL (HELLO-WORLD::Y 2.0) (HELLO-WORLD::Z 3.0))
Source: #P"=external="
-----------------------------------------------------------------------------
</pre>
</div>
</div>
<div id="outline-container-org9128413" class="outline-3">
<h3 id="org9128413"><span class="section-number-3">3.1.</span> Overloaded Functions</h3>
<div class="outline-text-3" id="text-3-1">
<p>
To expose overloaded functions, you have to cast the function pointer to the correct signature.
Suppose the function from the previous example was overloaded.
It would then need to be exposed as follows:
</p>
<div class="org-src-container">
<pre class="src src-C++">def("addThreeNumbers-double", (double(*)(double, double, double)) &addThreeNumbers),
</pre>
</div>
<p>
It is important that every function have a unique Lisp name - similar to name mangling in C++.
The convention we adopt in Clasp is to append type names to the original name.
</p>
</div>
</div>
</div>
<div id="outline-container-org50cf406" class="outline-2">
<h2 id="org50cf406"><span class="section-number-2">4.</span> Exposing Classes</h2>
<div class="outline-text-2" id="text-4">
<p>
Exposing a class is done via the class <code>class_</code>.
</p>
<p>
For example, say we have the class DoubleVector below:
</p>
<div class="org-src-container">
<pre class="src src-C++">class DoubleVector {
private:
vector<double> values;
public:
DoubleVector(int sz) {this->values.resize(sz);};
DoubleVector(const vector<double>& arg) {
this->fill(arg);
}
//...
};
</pre>
</div>
<div class="org-src-container">
<pre class="src src-C++">PACKAGE_USE("COMMON-LISP");
PACKAGE_NICKNAME("DV");
NAMESPACE_PACKAGE_ASSOCIATION(hw,HWPkg,"DOUBLE-VECTOR");
namespace dv {
CL_EXPOSE
void double_vector_startup() {
using namespace clbind;
package_ s("DV");
class_<DoubleVector>(s,"double-vector" )
//...
</pre>
</div>
<p>
This code creates a binding to the C++ class <code>DoubleVector</code>, with the name
<code>dv:double-vector</code> in Lisp.
This does not automatically creates a binding to the default constructor - <a href="#org5401a4e">use def_constructor for that</a>.
</p>
</div>
<div id="outline-container-org489072c" class="outline-3">
<h3 id="org489072c"><span class="section-number-3">4.1.</span> Inheritance</h3>
<div class="outline-text-3" id="text-4-1">
<p>
clbind can handle member functions of derived classes correctly, provided that they are all exposed.
To expose the inheritance structure of C++ classes, expose the base class,
and then use the following definition format for the derived class:
</p>
<div class="org-src-container">
<pre class="src src-C++">class_<CppDerivedClassName, CppBaseClassName>("lisp-class-name")
</pre>
</div>
<p>
If multiple inheritance brings in several base classes, use the following format:
</p>
<div class="org-src-container">
<pre class="src src-C++">class_<CppDerivedClassName, bases<CppBaseClassName1, CppBaseClassName2>>("lisp-class-name")
</pre>
</div>
<p>
If a base class is a pure virtual class, i.e. it has only pure virtual functions or its
constructor is private, make sure to use the <code>no_default_constructor</code> option when exposing
the base class, or you will get a compilation error.
</p>
</div>
</div>
<div id="outline-container-org5401a4e" class="outline-3">
<h3 id="org5401a4e"><span class="section-number-3">4.2.</span> Constructors</h3>
<div class="outline-text-3" id="text-4-2">
<p>
Add constructors to exposed classes with the function <code>def_constructor</code>:
</p>
<div class="org-src-container">
<pre class="src src-C++">template<typename... Types, typename... Policies>
class_& def_constructor(const string& name,
constructor<Types...> sig,
Policies... policies)
</pre>
</div>
<p>
In this function
</p>
<dl class="org-dl">
<dt>name</dt><dd>is the name of the constructor that will be visible in clasp. Again, it will be <a href="#org6d0a485">lispified</a>.</dd>
<dt>sig</dt><dd>is the parameter signature of the C++ constructor.
Use a comma-separated parameter-list list in the form <code>constructor<parameter-list>()</code>
of all the types used as parameters in the constructor you want to expose.</dd>
<dt>policies</dt><dd><a href="#org5880dea">7</a>.</dd>
</dl>
</div>
</div>
<div id="outline-container-orgf1d88c8" class="outline-3">
<h3 id="orgf1d88c8"><span class="section-number-3">4.3.</span> Member Functions</h3>
<div class="outline-text-3" id="text-4-3">
<p>
Exposing member functions is similar to exposing free functions.
Call the <code>class_</code> member function <code>def</code>:
</p>
<div class="org-src-container">
<pre class="src src-C++">template<class F, class... Policies>
class_& def(char const* name,
F fn,
Policies... policies )
</pre>
</div>
<p>
Thus exposing a member function is not different from <a href="#orgfe9b330">exposing free functions</a>, and the same arguments apply.
The exception to this rule is the lambda-list (arguments),
which always requires <code>self</code> as its first parameter,
which becomes the <code>this</code> argument within the method.
</p>
<div class="org-src-container">
<pre class="src src-C++">namespace dv {
CL_EXPOSE
void double_vector_startup() {
using namespace clbind;
package_ s("DV");
class_<DoubleVector>(s,"double-vector" )
. def_constructor("make-double-vector-with-size",constructor<int>())
. def_constructor("make-double-vector-with-values",constructor<const vector<double>&>())
. def("fill",&DoubleVector::fill)
. def("add",&DoubleVector::add)
. def("dot",&DoubleVector::dot)
. def("at",&DoubleVector::at)
. def("dump",&DoubleVector::dump);
}
};
</pre>
</div>
</div>
</div>
<div id="outline-container-org82565d9" class="outline-3">
<h3 id="org82565d9"><span class="section-number-3">4.4.</span> Static Member Function</h3>
<div class="outline-text-3" id="text-4-4">
<p>
As Common Lisp does not have the notion of static member functions,
exposing them is similar to <a href="#orgfe9b330">exposing free functions</a>.
</p>
</div>
</div>
<div id="outline-container-orgc515c5d" class="outline-3">
<h3 id="orgc515c5d"><span class="section-number-3">4.5.</span> Public Member Variables</h3>
<div class="outline-text-3" id="text-4-5">
<p>
Exposing public member variables works similar to exposing member functions.
</p>
</div>
</div>
<div id="outline-container-org34ba3e9" class="outline-3">
<h3 id="org34ba3e9"><span class="section-number-3">4.6.</span> Derivable classes</h3>
<div class="outline-text-3" id="text-4-6">
<p>
Some C++ libraries provide base classes that the library user is meant to subclass to add
additional application specific functionality.
For this situation Clasp, allows one to create classes in Common Lisp that derive from
these C++ classes, and implement methods that may be called from both C++ and Common Lisp code.
</p>
<p>
An example of this is within Clasp itself - where Clasp exposes <a href="https://clang.llvm.org/docs/LibASTMatchers.html">Clang's ASTMatchers library</a>.
Clasp exposes a facility of the Clang ASTMatcher library that evaluates callbacks on Clang's abstract syntax trees.
</p>
<p>
To make a class derivable, in place of <code>class_</code>, use <code>derivable_class_</code>, and provide two class template arguments.
The first template argument is a class that needs to be provided to clbind and is shown below (in this case <code>DerivableMatchCallback</code>).
The second template argument is the original library class that is to be subclassed (in this case <code>clang::ast_matchers::MatchFinder::MatchCallback</code>).
</p>
<div class="org-src-container">
<pre class="src src-C++">derivable_class_<DerivableMatchCallback, clang::ast_matchers::MatchFinder::MatchCallback> cl_bc(m,"MatchCallback",create_default_constructor);
cl_bc.def("run", &DerivableMatchCallback::default_run)
.def("onStartOfTranslationUnit", &DerivableMatchCallback::default_onStartOfTranslationUnit)
.def("onEndOfTranslationUnit", &DerivableMatchCallback::default_onEndOfTranslationUnit);
</pre>
</div>
<p>
The <code>DerivableMatchCallback</code> must be defined before the <code>derivable_class_</code> declaration above.
</p>
<div class="org-src-container">
<pre class="src src-C++">namespace asttooling {
class DerivableMatchCallback; // (1)
};
template <> // (2)
struct gctools::GCInfo<asttooling::DerivableMatchCallback> {
static bool constexpr NeedsInitialization = false;
static bool constexpr NeedsFinalization = false;
static GCInfo_policy constexpr Policy = unmanaged; // (3)
};
namespace asttooling {
class DerivableMatchCallback
: public clbind::Derivable<clang::ast_matchers::MatchFinder::MatchCallback> { // (4)
typedef clang::ast_matchers::MatchFinder::MatchCallback AlienBase; // (5)
public:
virtual void run(const clang::ast_matchers::MatchFinder::MatchResult &Result) { // (6)
const clang::ast_matchers::MatchFinderMatchResult conv(Result);
core::T_sp val = translate::to_object<const clang::ast_matchers::MatchFinderMatchResult &>::convert(conv);
core::eval::funcall(asttooling::_sym_run, this->asSmartPtr(), val);
}
void default_run(const clang::ast_matchers::MatchFinderMatchResult &Result) { // (7)
SIMPLE_ERROR(BF("Subclass must implement"));
};
virtual void onStartOfTranslationUnit() { // (8)
printf("%s:%d entered onStartOfTranslationUnit funcalling\n", __FILE__, __LINE__);
core::eval::funcall(_sym_onStartOfTranslationUnit, this->asSmartPtr());
}
void default_onStartOfTranslationUnit() {
printf("%s:%d entered default_onStartOfTranslationUnit\n", __FILE__, __LINE__);
this->AlienBase::onStartOfTranslationUnit();
}
void describe() { // (9)
printf("%s:%d Entered DerivableMatchCallback::describe()\n", __FILE__, __LINE__);
printf("this=%p typeid(this)@%p typeid(this).name=%s\n", this, &typeid(this), typeid(this).name());
printf("dynamic_cast<void*>(this) = %p\n", dynamic_cast<void *>(this));
printf("dynamic_cast<core::T_O*>(this) = %p\n", dynamic_cast<core::T_O *>(this));
printf("typeid(dynamic_cast<core::T_O>*>(this))@%p typeid.name=%s\n", &typeid(dynamic_cast<core::T_O *>(this)), typeid(dynamic_cast<core::T_O *>(this)).name());
printf("dynamic_cast<Derivable<clang::ast_matchers::MatchFinder::MatchCallback>*>(this) = %p\n", dynamic_cast<Derivable<clang::ast_matchers::MatchFinder::MatchCallback> *>(this));
printf("dynamic_cast<DerivableMatchCallback*>(this) = %p\n", dynamic_cast<DerivableMatchCallback *>(this));
printf("alien pointer = %p\n", this->pointerToAlienWithin());
printf("_Class: %s\n", _rep_(this->_Class).c_str());
for (size_t i(0); i < this->numberOfSlots(); ++i) {
printf("_Slots[%lu]: %s\n", i, _rep_(this->instanceRef(i)).c_str());
}
}
virtual ~DerivableMatchCallback() { // (10)
// Non trivial dtor
}
};
};
</pre>
</div>
<ol class="org-ol">
<li>A forward declaration of the <code>DerivableMatchCallback</code> class for the next piece, <code>GCInfo</code>.</li>
<li>A <code>gctools::GCInfo</code> template struct is used to tell the Clasp memory manager how to deal with this class. The NeedsInitialization field tell the memory manager that the DerivableMatchCallback::initialize() function must be called after the object is allocated. The NeedsFinalization field tells the memory manager that the destructor for this class needs to be registered with a finalizer. NeedsFinalization is used for resources like streams and anything that needs cleanup when it is collected. The Policy tell the memory manager how the memory for this object is managed.
<ol class="org-ol">
<li>Policy = normal means the object is managed by the memory manager: it can be collected and it can be moved.</li>
<li>Policy = collectable_immobile means the object can be collected by the memory manager but it cannot be moved.</li>
<li>Policy = atomic means the object contains no internal pointers (such as strings or integer vectors) and so it can be placed in special memory that doesn't need to be scanned during garbage collection.</li>
<li>Policy = unmanaged means the object will not be automatically collected and it cannot be moved.
This is used in special cases like static vectors.</li>
</ol></li>
<li>Instances of <code>DerivableMatchCallback</code> cannot be moved or automatically collected.
They need to be managed manually and carefully so that they do not leak memory.</li>
<li>The <code>DerivableMatchCallback</code> inherits from a special template class, <code>clbind::Derivable<clang::ast_matchers::MatchFinder::MatchCallback></code>.
This makes it inherit from both the C++ class <code>MatchCallback</code> and the Clasp <code>Instance_O</code>
class, which adds Common Lisp slots to the object.</li>
<li>The <code>AlienBase</code> type needs to be defined for <code>derivable_class_</code> to function.</li>
<li>The <code>virtual void run(...) {...}</code> method is defined by <code>clang::ast_matchers::MatchFinder::MatchCallback</code> and we need to overload it.
The body of this method translates the argument(s) into Common Lisp types and then invokes a Common Lisp function,
<code>core::eval::funcall(asttooling::_sym_run, this->asSmartPtr(), val)</code>,
that the programmer will define in Common Lisp.</li>
<li>The <code>void default_run(...)</code> method is a non-virtual method that is exposed to Common Lisp.
If a C++ base class defines the <code>run</code> method, then <code>default_run</code> should call it.
If no C++ base class defines the run method, then an error should be signalled,
and the programmer must provide a <code>run</code> method in Common Lisp.</li>
<li>In this example, the <code>onStartOfTranslationUnit~/~default_onStartOfTranslationUnit</code> are
another pair of functions that allow the user to overload an
on-start-of-translation-unit method from Common Lisp.</li>
<li>A <code>describe</code> method is provided to print internal information about a <code>DerivableMatchCallback</code> instance.</li>
<li>The <code>DerivableMatchCallback</code> class should have a destructor.</li>
</ol>
<p>
In the above example, the <code>run~/~default_run</code> pair of methods demonstrate what you need to
do to overload the <code>run</code> C++ method from Common Lisp.
</p>
<p>
In Common Lisp, to create a derived class one would use
</p>
<div class="org-src-container">
<pre class="src src-lisp">(defclass count-match-callback (ast-tooling:match-callback) () ;; (1)
(:metaclass core:derivable-cxx-class))
(core:defvirtual ast-tooling:run ((self count-match-callback) match) ;; (2)
(let* ((nodes (ast-tooling:nodes match))
(id-to-node-map (ast-tooling:idto-node-map nodes))
(node (gethash :whole id-to-node-map)))
(advance-match-counter)))
</pre>
</div>
<ol class="org-ol">
<li>The derived class is defined using <code>cl:defclass</code> as usual. It is a subclass of the
exposed class. It has the special metaclass <code>:metaclass core:derivable-cxx-class</code>.</li>
<li>The <code>core:defvirtual</code> macro is used to overload the <code>asttooling:run</code> method.
The overloaded method takes two arguments. The first argument is the instance, <code>self</code>,
and the second argument was passed from the C++ <code>run</code> virtual method.</li>
</ol>
</div>
</div>
</div>
<div id="outline-container-org2e18ff8" class="outline-2">
<h2 id="org2e18ff8"><span class="section-number-2">5.</span> Exposing Enums</h2>
<div class="outline-text-2" id="text-5">
<div class="org-src-container">
<pre class="src src-C++">
enum ColorEnum { red, green, blue };
void printColor(ColorEnum color) {
switch (color) {
case red:
printf("red\n");
break;
case green:
printf("green\n");
break;
case blue:
printf("blue\n");
break;
}
}
// Then - to expose it...
PACKAGE_NICKNAME("HW");
NAMESPACE_PACKAGE_ASSOCIATION(hw,HWPkg,"HELLO-WORLD");
SYMBOL_EXPORT_SC_(HWPkg,STARcolorTranslatorSTAR); // (1)
CLBIND_TRANSLATE_SYMBOL_TO_ENUM(ColorEnum, hw::_sym_STARcolorTranslatorSTAR ); // (2)
namespace hw {
CL_EXPOSE
void hello_world_startup() {
printf("Entered %s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__ );
using namespace clbind;
package_ s(HWPkg);
enum_<ColorEnum>(s,hw::_sym_STARcolorTranslatorSTAR) // (3)
.value("red",red) // (4)
.value("green",green)
.value("blue",blue);
s.def("printColor",&printColor); // (5)
}
</pre>
</div>
<ol class="org-ol">
<li>Export the symbol <code>*COLOR-TRANSLATOR*</code> from the <code>HELLO-WORLD</code> package.</li>
<li>Create a type translator that translates Common Lisp symbols into <code>ColorEnum</code> values.
If given a symbol without a corresponding enum value, an error is signaled.</li>
<li>Define the enum binding <code>ColorEnum</code>, and bind it to the symbol <code>HW:*COLOR-TRANSLATOR*</code>.</li>
<li>Define one enum value associating <code>ColorEnum::red</code> with the Lisp symbol <code>'HW:RED</code>.
The symbols for the enum values will be in the same package as the <code>HW:*COLOR-TRANSLATOR*</code>.</li>
<li>Expose a function that accepts <code>ColorEnum</code> values as its argument.</li>
</ol>
<p>
Then the enum can be used from within Clasp as follows:
</p>
<div class="org-src-container">
<pre class="src src-lisp">COMMON-LISP-USER> (hw:print-color 'hw:red)
red
COMMON-LISP-USER> (hw:print-color 'hw:green)
green
COMMON-LISP-USER> (hw:print-color 'hw:blue)
blue
COMMON-LISP-USER> hw:*color-translator*
#<SYMBOL-TO-ENUM-CONVERTER>
COMMON-LISP-USER>
</pre>
</div>
</div>
</div>
<div id="outline-container-org4f9e726" class="outline-2">
<h2 id="org4f9e726"><span class="section-number-2">6.</span> Translators</h2>
<div class="outline-text-2" id="text-6">
<p>
Translators are used to automatically convert C++ objects to Common Lisp objects and vice
versa. This is a convenience functionality, allowing for easier interoperation.
It is especially useful for small C++ classes and structs that are passed to and from
functions and are meant to be created on the fly. Instead of exposing them and then
creating and filling them from Common Lisp, it is often easier to write a translator,
e.g. from a list, which makes it possible to pass a list as a parameter in place of the
object. This list is then automatically converted to the respective C++ object by the
translator.
</p>
</div>
<div id="outline-container-orgb3ca3e4" class="outline-3">
<h3 id="orgb3ca3e4"><span class="section-number-3">6.1.</span> Translation from C++ objects to Common Lisp objects</h3>
<div class="outline-text-3" id="text-6-1">
<p>
Translating from C++ to Common Lisp objects is done by specializing the templated struct
<code>to_object</code>, in the namespace <code>translate</code>, to the type of the C++ object.
The static function member function <code>convert</code> of that struct takes an object of that type
as a parameter, and returns the Common Lisp object. The translator must appear in the C++
source code before any functions/methods are exposed that need to use it. Translators are
incorporated into the template code that clbind generates for each exposed function/method.
</p>
<p>
Here is an example defining a conversion from <code>std::pair<int,int></code> into a <code>cl:cons</code>. Once
this definition is in place, <code>def</code> can be used to expose C++ functions that take a
<code>std::pair<int,int></code> as a parameter.
</p>
<div class="org-src-container">
<pre class="src src-C++">namespace translate
{
template <>
struct to_object<std::pair<int,int>>
{
static core::T_sp convert(std::pair<int,int> arg)
{
core::Cons_sp cons = core::Cons_O::create(core::Integer_O::create(arg.first),
core::Integer_O::create(arg.second));
return cons;
}
};
};
</pre>
</div>
</div>
</div>
<div id="outline-container-org50ed06f" class="outline-3">
<h3 id="org50ed06f"><span class="section-number-3">6.2.</span> Translation from Common Lisp objects to C++ objects</h3>
<div class="outline-text-3" id="text-6-2">
<p>
Translating from Common Lisp to C++ objects is done by specializing the templated struct
<code>from_object</code>, in the namespace <code>translate</code>, to the C++ object type.
A constructor must be provided that takes the Common Lisp object as a parameter,
and writes the resulting C++ object into an object called <code>_v</code>.
<code>from_object::DeclareType</code> must be defined to be the C++ type in question.
</p>
<p>
Here is the converse of the above example, converting a Lisp cons into a <code>std::pair<int,int></code>.
</p>
<div class="org-src-container">
<pre class="src src-C++">namespace translate
{
template <>
struct from_object<std::pair<int,int>>
{
typedef std::pair<int,int> DeclareType; // (1)
DeclareType _v;
from_object(core::T_sp obj)
{
if (obj.consp()) {
this->_v = std::make_pair(core::clasp_to_int(CONS_CAR(obj)), // (2)
core::clasp_to_int(CONS_CDR(obj)));
}
TYPE_ERROR(obj,cl::_sym_Cons_O); // (3)
}
};
};
</pre>
</div>
<ol class="org-ol">
<li><code>DeclareType</code> is used by clbind, and must be defined in to the <code>from_object</code> type.</li>
<li>We store the translated result into the <code>_v</code> field.
This is so that if the argument is used as a return value from a Lisp function,
the value can be recovered from here.</li>
<li>If the type of <code>obj</code> doesn't match what this translator handles,
then signal a type error that tells the user what types are accepted.</li>
</ol>
</div>
<div id="outline-container-orge14f3b2" class="outline-4">
<h4 id="orge14f3b2"><span class="section-number-4">6.2.1.</span> Advanced from_object translators</h4>
<div class="outline-text-4" id="text-6-2-1">
<p>
<code>struct from_object</code> takes a second template argument that can have the
value <code>std::true_type</code> or <code>std::false_type</code>. The default is <code>std::true_type</code>, and
it means that the <code>_v</code> instance variable will be initialized by the <code>from_object</code>
</p>
<p>
constructor using the Common Lisp value in the <code>T_sp</code> constructor argument.
<code>std::false_type</code> is subtle - it is used to express the <code>pureOutValue<N></code> <a href="#org5880dea">policy</a>.
<code>std::false_type</code> means that the <code>from_object</code> translator does not initialize its <code>_v</code>
field. Instead, the field can be passed by reference to a function and written in to.
The wrapper will take the result out and return it as multiple return values.
</p>
<div class="org-src-container">
<pre class="src src-C++">template <>