File: pce2cpp.doc

package info (click to toggle)
swi-prolog-packages 5.0.1-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 50,688 kB
  • ctags: 25,904
  • sloc: ansic: 195,096; perl: 91,425; cpp: 7,660; sh: 3,046; makefile: 2,750; yacc: 843; awk: 14; sed: 12
file content (1016 lines) | stat: -rw-r--r-- 34,131 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
\section{Introduction}

\newcommand{\glb}[1]{{\bf #1}\index{#1}}

XPCE has been developed as a GUI environment that can easily be
connected to an arbitrary application language. Currently, XPCE is
targeted first of all to Prolog. The C++ interface described in this
document has been added to allow XPCE users using C++ for defining new,
high-performance, XPCE classes, or XPCE encapsulation of (OS) features
accessible from C/C++.

XPCE is a dynamically typed object-oriented system. (Graphical) objects
may be manipulated using the generic operations \cfunc{new}{} to create an XPCE
instance of an XPCE class, \cfunc{send}{} to invoke a `procedure' method on an
instance, \cfunc{get}{} for a `function' method and \cfunc{free}{} to destroy an object.

The interface between XPCE and an application language is responsible
for:

\begin{itemize}
    \item Conversion of application-language data to XPCE data
    \item Conversion of XPCE data to application-language data
    \item Calling the XPCE generic operations
    \item Allowing XPCE to call functionality in the application-language
\end{itemize}

XPCE has been successfully connected to various Prolog and Lisp systems.
These systems are also symbolically typed and the runtime environment
can map predicate/function-names onto the implementation (i.e. the
runtime environment can call a predicate/function given the name and
arguments).

The C++ language has neither of these features: if a function is
defined as untyped, there is no general way to find the type of the
actual arguments at runtime.  Also (within the language), C++ can't
map the \strong{name} of a function onto the address of the function.

The C++ \strong{compiler} however can reason about types and the
language allows for the definition of new types as well as the
conversion between types.  The interface described in this document
exploits these features to define an interface that is equally
robust and practical to use as the Prolog and Lisp interfaces.%
\footnote{We also considered a C-interface.  The C language both
	  lacks runtime and compile-time type-detection.  As a
	  consequence the user has to specify the appropriate type
	  conversions explicitly. This process is
	  considered too error-prone.}


\section{Motivation}

Below are a number of issues to motivate an interface to C++:

\begin{itemlist}
    \item [XPCE may be used as a graphical library for C++]
XPCE provides high-level support for dialog windows, but also for
interactive graphics, text and Unix process interaction.  In this
respect XPCE is an alternative for other C++ connected (GUI) libraries
with its own strong and weak points.

The learning-curve for GIU libraries is generally long due to the
large number of functions and options provided by such libraries.  If
XPCE can be connected to the language the application-programmer
prefers for a particular application, s/he does not have to learn a
new GUI library.

    \item [XPCE may be used as `glue' in a multi-language application]
XPCE can not only be connected to various different languages, it can
also be connected to various programming environments at the same time.

Each of the programming environments can call XPCE behaviour without
considering the language in which the behaviour is realised. For
example, C++ can activate an XPCE class defined in Prolog and visa
versa.

Time-critical and stable parts of the application may be modelled as
C++ defined XPCE classes, while the overall control of the application
may be defined in Prolog or Lisp.

    \item [C++ may be used to implement efficient XPCE classes]
When communicating with Prolog or Lisp, a considerable amount of time
is lost in data-transformations and control-transfer between XPCE and
the Prolog or Lisp environment.  With C++ this transformation is not
necessary, making C++ the ideal language for defining performance
critical XPCE classes.

    \item [Making other packages available to XPCE]
Many systems and libraries provide an interface to C and/or C++.
XPCE's C++ interface may be used as an efficient intermediate
between XPCE and such an (operating-) system or library.
\end{itemlist}


\section{Capabilities of the interface}

The interface between XPCE and C++ is fully transparent.  It allows
C++ code to create and manipulate XPCE objects. C++ functions can
be called from XPCE code objects so that the message of a button object
can call a C++ function {\bf and} pass arguments to this function.
Although, in principle, this interface suffices for defining XPCE
classes in C++, a more friendly and efficient mechanism is provided for
this.

The interface is built around the C++ class \cclass{PceArg}.  An instance
of this class represents an anonymous XPCE object. Class \cclass{PceArg}
defines member functions that allow the C++ programmer to activate PCE
methods on the object. Class PceArg also defines the type-conversion
between raw C data-types and XPCE's dynamically typed data objects.

\section{Argument-type conversion}

\subsection{C to XPCE}

The C++ class \cclass{PceArg} defines constructors for translating raw C
data-types into dynamically-typed XPCE data objects.  The mapping
defined by these constructors is given in \tabref{c2pce}.

\begin{table}
\begin{center}
\begin{tabular}{|l|l|}
\hline
\bf C			& \bf XPCE \\
\hline
char, short, int, long	& int \\
char *			& name object \\
float, double		& real object \\
\hline
\end{tabular}
\end{center}
\caption{Conversion of C data into XPCE data objects}
\label{tab:c2pce}
\end{table}

\subsection{XPCE to C}

The C++ class \cclass{PceArg} defines cast operators to convert
dynamically typed XPCE data objects into primitive C objects. These cast
operators define the mapping given in \tabref{pce2c}. If the requested
type is \type{char *}, the value should be copied unless the converted
object is \strong{known} to be an XPCE name object.

\begin{table}
\begin{center}
\begin{tabular}{|l|l|p{3in}|}
\hline
\bf requested C-type	& \bf XPCE 	& Remarks\\
\hline
int			& int, number  	& PCE int only has 30 bits \\
int			& real	   	& rounded value \\
int			& char_array	& value if convertible \\
float, double		& real		& real is a float \\
float, double		& int, number	& converted value \\
float, double		& char_array	& value if convertible \\
char *			& name		& pointer to const char * \\
char *			& string	& pointer is valid as long as
					  string lives \\
char *			& int, number	& '\%d' formatted value in static
					  area \\
char *			& real		& '\%g' formatted value in static
					  area \\
\hline
\end{tabular}
\end{center}
\caption{Conversion of XPCE data objects to C}
\label{tab:pce2c}
\end{table}

C++ interface functions that pass control to XPCE generally accept
arguments of the type \cclass{PceArg}. The C++ type-conversion mechanism
ensures that the C-primitive types are passed correctly to XPCE. The
user should provide additional cast operators for application-types.
Examples of using type-conversions are given in the subsequent sections.


\subsection{Pointers}

C-Pointers may be represented using the XPCE class \class{c_pointer}.
On various occasions, C++ applications will have to store pointers
to C++ data in XPCE, for example to pass the value of \const{this}
to a \cclass{PceCall}.  See \secref{cppmethod}.  The interface defines
\cclass{PcePointer} in \file{<pce/Pointer.h>}.  \cclass{PcePointer} is
a derived class from \cclass{PceArg}.  The value of a \cclass{PceArg}
that represents a pointer is extracted using \cfunc{PceArg::pointer}{}.

\begin{description}
    \cfunction{}{PcePointer::PcePointer}{void *ptr}
Encapsulate a C/C++ pointer into an XPCE \class{c_pointer} object and
return a reference to the latter.

    \cfunction{void *}{PceArg::pointer}{}
If the argument contains a \class{c_pointer} object, return the value
of the pointer.  Otherwise return \const{NULL}.
\end{description}


\section{Invoking XPCE methods}

Besides type-conversion, the C++ class \cclass{PceArg} defines the
generic XPCE operations \cfunc{send}{}, \cfunc{get}{} and \cfunc{free}{}
as member functions. The PCE \cfunc{send}{} and \cfunc{get}{} operations
take a list of arguments. Up to 10 arguments may be specified using
overloaded versions of the member functions \cfunc{send}{} and
\cfunc{get}{} as defines on class \cclass{PceArg}. More arguments may be
specified using \cfunc{sendv}{} and \cfunc{getv}{} that accept an array
of arguments.

The following examples show how the x-coordinate of the \cclass{PceArg}
object `point' is changed and how the selection of a text-item
is changed:

\begin{code}
   PceArg point, text_item;
   ...
   point.send("x", 10);
   text_item.send("selection", "gnat");
   ...
\end{code}

The member function \cfunc{PceArg::send}{} takes arguments of the type
\cclass{PceArg}. The first argument of \cfunc{send}{} is interpreted as the
selector, while the remaining arguments are interpreted as the arguments
to the send-operation. The argument \verb$10$ is converted into an XPCE
\type{int} datum, while the \verb$"gnat"$ argument is converted into an
XPCE name object.

\index{PceStatus}\index{enum}\index{status information}%
The member function \cfunc{PceArg::send}{} returns a value of the
\jargon{enum} type \type{PceStatus}:

\begin{code}
enum PceStatus { FAIL = 0, SUCCEED = 1 };
\end{code}

The member function \cfunc{PceArg::get}{} invokes the XPCE generic
operation \cfunc{get}{}. The return value is made available as a
\cclass{PceArg} again. The global object \glb{TheDisplay} refers to what
is called @display for the Prolog and Lisp interfaces. The following
code fragment identifies XPCE:

\begin{code}
void
identifyPce()
{ TheDisplay.send("inform", "I am XPCE version %s",
		  ThePce.get("version"));
}
\end{code}

Finally, the member function \cfunc{PceArg::free}{} invokes the
generic XPCE operation \cfunc{free}{} to discard of the XPCE object.  It is
equivalent to \exam{obj.send("free")}, except the \cfunc{free}{} may be 
used on objects that are already freed.

\begin{description}
    \cfunction{PceStatus}{PceArg::send}{PceArg selector, ..., PceArg argN, ...}
Invoke an XPCE send operation. The first argument is used as the
selector, and the remaining arguments are used as arguments to the
method.  Using the conversion of \type{char *} to \cclass{PceArg}, the
selector can be written as, for example, \verb$"append"$. If performance
is critical, it is better to store the converted value in a global C++
object:

\begin{code}
static PceArg PcNappend("append");

	...,
	gnat.send(PcNappend, ...)
	...,
\end{code}

The \program{PceEmacs} C++ mode contains commands to gather and replace
all selectors in a file.

    \cfunction{PceArg}{PceArg::get}{PceArg selector, ..., PceArg argN, ...}
Similar to \cfunc{PceArg::send}{}, but implements the XPCE get
operation.  As the result is a \cclass{PceArg} as well, multiple get
operations may be concatenated:

\begin{code}
    { int screenwidth = TheDisplay.get("size").get("width");
      ...,
\end{code}

    \cfunction{PceStatus}{PceArg::free}{}
Invokes ->free on the receiver if the object exists. Succeeds if the
object is not protected by `object ->protected'. Succeeds silently if
the receiver is no object (i.e.\ an integer), or has already been freed.
\end{description}

\section{Creating objects}

The C++ interface defines derived classes of class \cclass{PceArg} with
different constructors for creating XPCE objects.  The most generic
of this is the C++ class \cclass{PceObject}.  The first argument (of
type \cclass{PceArg}) defines the name of the XPCE class from which
an instance is to be created.  The remaining argument define the
arguments given to the XPCE ->initialise method.  The following
fragment defines a dialog windows saying hello to the world:

\index{hello world}
\begin{code}
void
hello()
{ PceObject d("dialog");	// Create an instance of dialog

  d.send("append", PceObject("label", "message", "Hello World"));
  d.send("open");
}
\end{code}

\index{header files,for classes}
Although the expression \exam{PceObject("<classname>", ...} may be used
to create objects, there are C++ header files for each of the built-in
XPCE classes that define a derived class Pce<CapitalisePceClassName>.
These classes define constructors for all possible arities ($< 10$) of
the class' initialisation method. For example PcePoint (representing an
XPCE point object) defines constructors with 0, 1, and 2 arguments as
`point ->initialise' accepts two optional arguments.

Below is a rewritten version of the hello world program that also
allows the user to delete the window.

\begin{code}
#include <pce/Pce.h>
#include <pce/Label.h>
#include <pce/Button.h>
#include <pce/Message.h>
#include <pce/String.h>

void
hello2()
{ PceDialog d;			// Create an instance of dialog

  d.send("append", PceLabel("message", PceString("Hello World")));
  d.send("append", PceButton("quit", PceMessage(d, "destroy")));
  d.send("open");
}
\end{code}

Some XPCE classes have names that cannot be represented as C++
symbols.  \Tabref{cppclassnames} defines these names.

\begin{table}
\begin{center}
\begin{tabular}{|l|l|l|}
\hline
\bf XPCE name	& \bf C++ Name	& \bf Summary \\
\hline
\verb$*$	& PceTimes	& Multiplication expression \\
\verb$-$	& PceMinus	& Subtraction expression \\
\verb$+$	& PcePlus	& Addition expression \\
\verb$/$	& PceDivide	& Division expression \\
\verb$:=$	& PceBinding	& Name-value pair for argument-list \\
\verb$<$	& PceLess	& Compare expressions on less-then \\
\verb$=$	& PceEquation	& Identity between two expressions \\
\verb$=<$	& PceLessEqual	& Compare expressions on less-or-equal \\
\verb$==$	& PceEqual	& Test equivalence of arguments \\
\verb$>$	& PceGreater	& Test arithmetic $>$ \\
\verb$>=$	& PceGreaterEqual & Compare expressions on greater-or-equal \\
\verb$?$	& PceObtain	& Invoke a get method \\
\verb$\==$	& PceNonEqual	& Test non-equivalence of arguments \\
\hline
\end{tabular}
\end{center}
\caption{C++ classnames for XPCE classes with a `symbol' name}
\label{tab:cppclassnames}
\end{table}

\subsection{Global (named) objects}

\index{global objects}%
The C++ derived class \cclass{PceGlobal} allows access to existing named
PCE objects (@display, @arg1, etc.) and allows for the definition of
new named objects.  The constructor arguments are:

\begin{code}
PceGlobal::PceGlobal(PceArg name, [PceArg class, PceArg arg1 ...])
\end{code}

Some commonly used global objects are bound to globally defined
instances of the C++ class \cclass{PceGlobal}.  They are listed in
\tabref{globals}.

\begin{table}
\begin{center}
\begin{tabular}{|l|l|l|}
\hline
\bf Prolog/lisp name	& C++ name 		& Remarks\\
\hline
@display		& \glb{TheDisplay}	& Represents the X-display \\
@pce			& \glb{ThePce}		& Represents the environment \\
@nil			& \glb{TheNil}		& Nil, nothing \\
@default		& \glb{TheDefault}	& Default value \\
@on			& \glb{TheOn}		& Boolean true \\
@off			& \glb{TheOff}		& Boolean false \\
@receiver		& \glb{TheReceiver}	& Receiver of event/method \\
@event			& \glb{TheEvent}	& Current event \\
@arg1 ... @arg10	& \glb{TheArg1} \ldots \glb{TheArg10} & Forwarded arguments \\
\hline
\end{tabular}
\end{center}
\caption{Global instances of PceGlobal}
\label{tab:globals}
\end{table}

\section{Callback to a C++ function}

In the sections above, we have discussed how the C++ class
\cclass{PceArg} and its derived classes are used to create an access
objects in the XPCE world from C++. This section describes how a C++
function can be called from XPCE. 

\index{call-back (C++)}%
The C++ class \cclass{PceCall} is a derived class of \cclass{PceArg}.  It
creates an XPCE code object that, when executed, calls a C++ function.
\cclass{PceCall} `encapsulates' the C++ function in an object that may
be activated from XPCE.  The following example illustrates this:

\begin{code}
#include <pce/Pce.h>
#include <pce/Dialog.h>
#include <pce/TextItem.h>

PceStatus
showInstances(PceArg cl)
{ PceArg c;

  if ( (c = ThePce.get("convert", cl, "class")) )
  { TheDisplay.send("inform", "Class %s has %d instances",
		    c.get("name"), c.get("no_created") -
		    c.get("no_freed"));
  }

  return SUCCEED;
}


PceStatus
pceInitApplication(int argc, char *argv[])
{ PceDialog d("Show #Instances");

  d.send("append", PceTextItem("class", "",
			       PceCall(showInstances, TheArg1)));
  return d.send("open");
}

\end{code}

The C++ class \cclass{PceFuncall} is similar to \cclass{PceCall}, but the
return value of the C++ function is a \cclass{PceArg}.  The resulting code
object is an XPCE function object.  Such an object may be used from
another language (e.g.\ Prolog) or as part of other code objects for,
for example, a button.  The following example defines @getenv as
a function to fetch a Unix environment variable.

\label{getenv}
\begin{code}
#include <pce/Pce.h>
#include <stdlib.h>

PceArg
PceGetenv(PceArg name)
{ char *s = getenv(name);

  if ( s )
    return s;
  else
    return FAIL;
}


PceStatus
pceInitApplication(int argc, char *argv[])
{ PceFuncall f(PceGetenv, TheArg1);

  f.send("_name_reference", "getenv");  // name the object @getenv

  return SUCCEED;
}
\end{code}


The fragment below shows how this code is made available to
Prolog:

\begin{code}
1 ?- pce_load_cxx(getenv).

2 ?- get(@getenv, '_forward', 'USER', X).

X = jan
\end{code}


\subsection{Callback to a C++ member function}	\label{sec:cppmethod}

If an application is written using C++ classes and member functions and
one wishes to add XPCE behaviour to this class, it would be desirable
to pass \const{this} and a pointer to a C++ member function to XPCE
for later callback.

Such as system has been implemented in version 0.1 of this interface.
This implementation relied on undefined implementation features of
\program{g++}, where a C++ member function is basically a C function,
where the first argument is a pointer to \const{this}. In \program{g++},
a pointer to a member function can be taken and casted to other types.

This implementation is not portable, and cannot even be guaranteed for
future versions of \program{g++}, which is why we decided to drop the
support for calling C++ member functions directly from XPCE.

If calling a member function cannot be avoided, use \cclass{PceCall()}
to call a wrapper C++ function that calls the specific member function.
The example \file{person.cxx} exploits this technique, which is
summarised in the example below.  \cclass{PcePointer} is used to
pack the \const{this} pointer into an XPCE object of class
\class{c_pointer}.  \cfunc{PceArg::pointer}{} is used to extract the
pointer value.

\begin{code}
class person
{
  char *name;
public:

  setname(char *n) { name = n; }
  char *getname()  { return name; }

  void edit();
};


// The XPCE/C++ wrapper
PceStatus
setNamePerson(PceArg person, PceArg name)
{ (class person *)p = (class person *)person.pointer();

  p->setname(name);

  return SUCCEED;
}


// And the simple edit control
person::edit()
{ TextItem ti("name", name,
	      PceCall(setNamePerson, PcePointer(this), TheArg1));

  ti.send("open");
}
\end{code}


\section{Defining an XPCE class in C++}

The previous sections illustrate how the XPCE library may be used from
a C++ application.  Although C++ functionality can be made available to
users of other languages using \cclass{PceCall} and friends, this is often
not the desirable way (c.f.\ the clumsy way to define and call the
@getenv function on page~\pageref{getenv}).

A more natural way to make C++ functionality available to users of other
languages is by defining a XPCE class from C++.  The definition of a
XPCE class consists of C++ functions implementing the XPCE methods, a
C++ function to build the XPCE class object and finally a call to XPCE
to let XPCE know the class can be built by calling this function.

\subsection{An XPCE-method function}

A C++ function that implements a method of an XPCE class returns a
\type{PceStatus} for a send-method and an \cclass{PceArg} for a
get-method. The first argument is an instance of the C++ class
\cclass{PceReceiver}, a subclass of \cclass{PceArg}. All remaining
arguments are instances of \cclass{PceArg}. \cclass{PceReceiver} defines
member-functions for fast access to instance-variables:

\begin{description}
    \cfunction{PceArg}{PceReceiver::fetch}{PceVariable var}
Fetches the value of the indicated instance-variable.  \arg{var} is
normally stored in a global variable which is initialised by
\cfunc{PceClass::defvar}{}.  This function realises `object <-slot'.

    \cfunction{PceStatus}{PceReceiver::store}{PceReceiver var, PceArg value}
Stores the value of an instance variable.  If this function fails, it
indicates that \arg{value} could not be converted to the type of the
instance variable.  This function realised `object ->slot'.

    \cfunction{PceStatus}{PceReceiver::sendSuper}{PceArg ...}
Invokes a method using the definition of the super-class of the class on
which the currently invoked method is defined.  See `object ->send_super'.

    \cfunction{PceArg}{PceReceiver::getSuper}{PceArg ...}
As \cfunc{PceReceiver::sendSuper}{}, but for get-methods.  See
`object <-get_super'.
\end{description}

The example below is a typical example, combining various of the
above features:

\begin{code}
PceStatus
initialiseApp(PceReceiver a, PceArg client)
{ a.sendSuper("initialise", "I am a toplevel window");
  a.store(VarClient, client);
  a.send("append", PceDialog());

  return TRUE;
}
\end{code}

\subsection{Declaring the XPCE class}

The C++ class \cclass{PceClass} is a derivate of \cclass{PceArg} for defining
new XPCE classes.  It defines the following member-functions:

\begin{description}
   \cfunction{PceVariable*}{PceClass::defvar}{name, group, summary, type,
					      access, initial)}
All arguments are of the type \cclass{PceArg}.  See XPCE manual on class
variable and `class ->instance_variable' for details.

   \cfunction{PceStatus}{PceClass::defsendmethod}{name, group, summary,
						  function, type ...)}
All arguments are of the type \cclass{PceArg}.  function is a pointer to a
function that returns a \type{PceStatus}, which first argument is a \cclass{PceReceiver} and which has the same number of \cclass{PceArg} arguments as
there are `types' provided (maximum 10).

   \cfunction{PceStatus}{PceClass::defgetmethod}{name, group, summary,
						 rtype, function, type ...)}
Similar to \cfunc{PceClass::defsendmethod}{}.  The argument \arg{rtype} is a
type defining the return-type.  The return-type of the C++ function is
\cclass{PceArg}.
\end{description}

Class \cclass{PceClass} defines two constructors: with a single argument
it looks up an existing class object of the specified name. With 4
arguments it declares a C++ definition of a class. The arguments are:
name of the class, name of the super-class, summary description and
pointer to a function to build the class. This function returns
\cclass{PceArg} and takes an (virgin) \cclass{PceClass} as argument. See
the example below.


\subsection{Example: Binary Tree}

The example below exploits all the mechanisms described above to define
an XPCE class \class{b_node}: a node in a binary tree.

\begin{code}
#include <pce/Pce.h>

// References to XPCE instance variables of the class.

static PceVariable *bnode_left;
static PceVariable *bnode_right;
static PceVariable *bnode_key;
static PceVariable *bnode_value;

// Method to initialise the instance (like a C++ constructor)

static PceStatus
initialiseBNode(PceReceiver n, PceArg key, PceArg value)
{ n.store(bnode_key, key);
  n.store(bnode_value, value);

  return SUCCEED;
}


// Send method to insert a new key/value pair into the tree

PceStatus
insertBNode(PceReceiver n, PceArg key, PceArg value)
{ int c = strcmp(n.fetch(bnode_key), key);

  if ( c == 0 )				/* replace value */
    return n.store(bnode_value, value);

  PceArg n2 = n.fetch(c > 0 ? bnode_right : bnode_left);
  if ( n2 != TheNil )
    return insertBNode(n2, key, value);

  return n.store(c > 0 ?  bnode_right : bnode_left,
		 PceObject("b_node", key, value));
}


// Method to find a node from a key.

PceArg
getNodeBNode(PceReceiver n, PceArg key)
{ int c = strcmp(n.fetch(bnode_key), key);

  if ( c == 0 )
    return n;

  PceArg n2 = n.fetch(c > 0 ? bnode_right : bnode_left);

  if ( n2 != TheNil )
    return getNodeBNode(n2, key);

  return FAIL;
}


// C++ function to build the XPCE class definition

PceStatus
makeClassBNode(PceClass cl)
{ bnode_left =
    cl.defvar("left", "tree", "Node to my left",
	      "b_node*", "get", TheNil);
  bnode_right =
    cl.defvar("right", "tree", "Node to my right",
	      "b_node*", "get", TheNil);
  bnode_key =
    cl.defvar("key", "table", "Key-name of the node",
	      "name", "get", TheNil);
  bnode_value =
    cl.defvar("value", "table", "Value of the node",
	      "any", "get", TheNil);

  cl.defsendmethod("initialise", "oms", "Create from key and value",
		   initialiseBNode, "key=name", "value=any");
  cl.defsendmethod("insert", "edit", "Add entry to the table",
		   insertBNode, "key=name", "value=any");
  
  cl.defgetmethod("node", "lookup", "Lookup node from key",
		   "b_node", getNodeBNode, "key=name");

  return SUCCEED;
}
  
	    
// let a C++ global constructor declare the class

PceClass ClassBNode("b_node", "object", "Node of a binary tree",
		    makeClassBNode);
\end{code}

\section{Lifetime of C++ objects and XPCE objects}

All C++ classes involved in defining the interface define a single
member: the \type{void *} `self'.  They represent no more than a
\strong{reference} to the XPCE object.  Creation of a C++ \cclass{PceArg}
instance does not automatically imply creation of an XPCE object and
deleting the \cclass{PceArg} object has no consequences for the XPCE
object.

Using constructors and destructors of PceArg objects can possibly
be used to help the incremental garbage collector of XPCE.  This is
still subject of study.


\section{Linking C++ code to XPCE}

\subsection{Incremental linking to Prolog}

To link an piece of C-code to XPCE/Prolog, the XPCE/C++ is best compiled
into a \idx{shared object} (Unix) or a \idx{Dynamic Load Library} (Windows),
which can then be loaded into the running XPCE/Prolog system using
Prolog's primitives for loading such files.  Normally, no function needs
to be called in the library.

The required system features are supported in Unix systems using the
\idx{ELF} binary format (\idx{Solaris 2.x}, \idx{Irix 5.x}, \idx{Linux})
and Win32 (Windows 95/NT). Except for platform specific problems, the
following sequence should suffice for creating a compliant \fileext{so}
file from an XPCE C++ class using \program{g++}.

\begin{code}
% g++ -c -fpic -I$PCEHOME/include myfile.C
% g++ -o myfile.so -shared myfile.o
\end{code}

On Windows systems, the C++ files must be compiled and linked with
the import library \file{xpce.lib} to a \fileext{DLL} file.  The
Windows binary is compiled with \program{MSVC 4.2}.

On modern operating systems, C++ global constructors will automatically
be executed when the shared object is loaded into the running
application.

The XPCE/Prolog library \pllib{pce_loadcxx} defines the predicate
pce_load_cxx/1 to load a shared object or DLL file:

\begin{description}
    \predicate{pce_load_cxx}{1}{+FileSpec}
Load the shared object holding an XPCE class.  This predicate is
provided for both SWI-Prolog and Quintus Prolog.  XPCE/C++ code
can also be part of normally Prolog foreign files and be loaded
using the Prolog native foreign file loading predicates.

The following is a typical example of the header of a Prolog file
using a C++ defined XPCE class.

\begin{code}
:- module(mymodule, []).
:- use_module(library(pce)).
:- require([ pce_load_cxx/1
	   ]).

:- initialization
   pce_load_cxx(foreign(mycxxcode)).

...
\end{code}
\end{description}


\subsection{C++ stand-alone applications}

Programs can be linked to a C++/XPCE stand-alone application by linking
the \fileext{o} files to the \clib{XPCEmain} and \clib{XPCE} libraries.
The \clib{XPCEmain} library contains a stub \cfunc{main}{} function that
initialises XPCE, and calls \cfunc{pceInitialiseApplication}{int argc,
char *argv[]}, passing the main arguments \arg{argc} and \arg{argv}.
Finally it enters a loop waiting for user-events and dispatching them.
This loop terminates if there are no more toplevel \class{frame} objects
on the current display. The application can be terminated explicitly by
invoking `@pce ->die', or calling \cfunc{exit}{}. Below is the (Unix)
sourcecode of \file{main.cxx}, the only member of \clib{XPCEmain}. This
file is available as \file{<pcehome>/src/itf/pcemain.cxx}

\begin{code}
#include <pce/Pce.h>
#include <pce/Chain.h>

static PceArg PcNframes("frames");
static PceArg PcNkind("kind");
static PceArg PcNtoplevel("toplevel");

extern "C" {
int	pceInitialise(int handles, char *home, int argc, char **argv);
int	pceDispatch(int fd, int timeout);
void	Cprintf(const char *fmt, ...);
}

int
main(int argc, char* argv[])
{ int frames = TRUE;

  if ( !pceInitialise(0, (char *)0, argc, argv) )
  { Cprintf("Sorry, failed to initialise XPCE\n");
    exit(1);
  }
  
  if ( !pceInitApplication(argc, argv) )
  { Cprintf("Failed to run pceInitApplication()\n");
    exit(1);
  }

  while(frames)
  { PceCell cell;

    pceDispatch(0, 1000);

    for(frames = FALSE, cell = AsChain(TheDisplay.get(PcNframes)).head();
	cell;
	++cell)
    { if ( cell.value().get(PcNkind) == PcNtoplevel )
      { frames = TRUE;
	break;
      }
    }
  }

  exit(0);
}
\end{code}

An XPCE/C++ stand-alone executable needs to be able to find the XPCE
home directory for the system-required bitmaps, the resources and the
PostScript header file.  The path to the home directory is provided
as second argument to \cfunc{pceInitialise}{}, or read from the
environment variable \env{PCEHOME}.


\subsubsection{Stand-alone applications in Win32}

The above also works on Windows platforms. \file{main.cxx} contains a
definition for \cfunc{WinMain}{} that parses the commandline arguments
and calls \cfunc{main}{} as described above. If the stand-alone Windows
applications wants to write or read to/from standard I/O, the system
will automatically allocate a console using Windows
\cfunc{AllocConsole}{} API.

\section{Goodies}

This section defines some member functions and types for speeding
up some operations and/or providing shorthands.


\subsection{Arithmetic on class PceArg}

Class \cclass{PceArg} defines integer arithmetic by overloading the
operators +, -, *, /, ++, --, +=, -=, *= and /=.  These functions yield
an error if one of the operands cannot be translated into an integer.
The following example defines an XPCE callable function that draws an
array of boxes.

\begin{code}
#include <pce/Pce.h>
#include <pce/Box.h>
#include <pce/Point.h>
#include <pce/Picture.h>

PceStatus
drawBoxes(PceArg dev, PceArg x, PceArg y, PceArg w, PceArg h, PceArg n)
{ while(n-- > 0)
  { dev.send("display", PceBox(w, h), PcePoint(x, y));
    x += w;
  }
  
  return SUCCEED;
}

PceStatus
pceInitApplication(int argc, char *argv[])
{ PcePicture p;
  
  drawBoxes(p, 10, 10, 20, 50, 20);
  p.send("open");

  return SUCCEED;
}
\end{code}


\subsection{Enumerating cells of a PCE chain}

The following functions allow for enumerating the elements of a list
similiar to `chain ->for_all' and friends.

\begin{description}
    \cfunction{PceCell}{PceChain::head}{}
Returns a reference to the first cell of the chain.  The C++ class
\cclass{PceCell} is \strong{no} derivate of \cclass{PceArg}.
    \cfunction{PceArg}{PceCell::value}{}
Returns the value of the cell.
    \cfunction{PceArg}{PceCell::operator ++}{}
Prefix \verb$++$.  Modifies the \cclass{PceCell} object to point to
the next cell in the XPCE chain.
    \cfunction{PceArg}{PceCell::operator ++}{int}
Postfix \verb$++$. Modifies the \cclass{PceCell} object to point
to the next cell in the XPCE chain, returns a new \cclass{PceCell}
object pointing to the old cell.  Use \exam{++cell} if you can.
\end{description}

The following example lists the (sub-) directories and files in the
argument directories. It uses the XPCE `chain->for_all' for the
directories, and C++ Cell methods for the files.

\begin{code}
#include <stdlib.h>
#include <pce/Pce.h>
#include <pce/Chain.h>
#include <pce/Directory.h>
#include <pce/Message.h>
#include <iostream.h>

PceStatus
pceInitApplication(int argc, char *argv[])
{ int i;

  for(i=1; i < argc; i++)
  { PceDirectory d(argv[i]);

    PceChain dirs = AsChain(d.get("directories"));
    cout << "sub directories of " << argv[i] << endl;
    dirs.send("for_all", PceMessage(ThePce, "write_ln", TheArg1));

    PceChain files = AsChain(d.get("files"));
    cout << "files in " << argv[i] << endl;
    PceCell cell;

    for( cell = files.head(); cell; )
      cout << (char *)(++cell).value() << endl;
  }

  ThePce.send("die");
}
\end{code}

While \cclass{PceCell} references contain valid references to cells
of XPCE chains, the contents of the chain may \strong{not} be manipulated.

\subsection{Debugging (pretty print)}

\index{pretty printing}
\begin{description}
    \cfunction{char *}{PceArg::pp}{}
The member function \cfunc{PceArg::pp}{} returns a description of the
argument in the same style as the the XPCE debugger. The storage is
provided by a ring of 16 buffers. This implies that upto 16 arguments
may use \cfunc{pp}{} without overwriting each others output. If
information has to be kept it must be copied.
\end{description}


\section{Status}

The status of the XPCE/C++ interface should be regarded alpha.  The
basic concept will probably not change, neither will the mechanisms
for creating objects, sending messages, etc.  Various things are
not yet provided for:

\begin{itemize}
    \tick{Incremental garbage collector interface}
This can probably be integrated into the constructors and destructors
of the various C++ classes.  As omitting this just leaves garbage around
for a little too long there is no reason to hurry.
    \tick{More `goodies'}
It may prove useful to define more `goodies', both to provide shorthands
for commonly used operations and to provide low-level fast access to
the XPCE virtual machinery.
\end{itemize}