Debian Codegraph @

gcc/ada/doc/gnat_rm/interfacing_to_other_languages.rst

raw
1 .. _Interfacing_to_Other_Languages:
2
3 ******************************
4 Interfacing to Other Languages
5 ******************************
6
7 The facilities in Annex B of the Ada Reference Manual are fully
8 implemented in GNAT, and in addition, a full interface to C++ is
9 provided.
10
11 .. _Interfacing_to_C:
12
13 Interfacing to C
14 ================
15
16 Interfacing to C with GNAT can use one of two approaches:
17
18 *
19 The types in the package ``Interfaces.C`` may be used.
20 *
21 Standard Ada types may be used directly. This may be less portable to
22 other compilers, but will work on all GNAT compilers, which guarantee
23 correspondence between the C and Ada types.
24
25 Pragma ``Convention C`` may be applied to Ada types, but mostly has no
26 effect, since this is the default. The following table shows the
27 correspondence between Ada scalar types and the corresponding C types.
28
29
30 ======================== ==================================================================
31 Ada Type C Type
32 ======================== ==================================================================
33 ``Integer`` ``int``
34 ``Short_Integer`` ``short``
35 ``Short_Short_Integer`` ``signed char``
36 ``Long_Integer`` ``long``
37 ``Long_Long_Integer`` ``long long``
38 ``Short_Float`` ``float``
39 ``Float`` ``float``
40 ``Long_Float`` ``double``
41 ``Long_Long_Float`` This is the longest floating-point type supported by the hardware.
42 ======================== ==================================================================
43
44 Additionally, there are the following general correspondences between Ada
45 and C types:
46
47 *
48 Ada enumeration types map to C enumeration types directly if pragma
49 ``Convention C`` is specified, which causes them to have a length of
50 32 bits, except for boolean types which map to C99 ``bool`` and for
51 which the length is 8 bits.
52 Without pragma ``Convention C``, Ada enumeration types map to
53 8, 16, or 32 bits (i.e., C types ``signed char``, ``short``,
54 ``int``, respectively) depending on the number of values passed.
55 This is the only case in which pragma ``Convention C`` affects the
56 representation of an Ada type.
57
58 *
59 Ada access types map to C pointers, except for the case of pointers to
60 unconstrained types in Ada, which have no direct C equivalent.
61
62 *
63 Ada arrays map directly to C arrays.
64
65 *
66 Ada records map directly to C structures.
67
68 *
69 Packed Ada records map to C structures where all members are bit fields
70 of the length corresponding to the ``type'Size`` value in Ada.
71
72 .. _Interfacing_to_C++:
73
74 Interfacing to C++
75 ==================
76
77 The interface to C++ makes use of the following pragmas, which are
78 primarily intended to be constructed automatically using a binding generator
79 tool, although it is possible to construct them by hand.
80
81 Using these pragmas it is possible to achieve complete
82 inter-operability between Ada tagged types and C++ class definitions.
83 See :ref:`Implementation_Defined_Pragmas`, for more details.
84
85 :samp:`pragma CPP_Class ([Entity =>] {LOCAL_NAME})`
86 The argument denotes an entity in the current declarative region that is
87 declared as a tagged or untagged record type. It indicates that the type
88 corresponds to an externally declared C++ class type, and is to be laid
89 out the same way that C++ would lay out the type.
90
91 Note: Pragma ``CPP_Class`` is currently obsolete. It is supported
92 for backward compatibility but its functionality is available
93 using pragma ``Import`` with ``Convention`` = ``CPP``.
94
95
96 :samp:`pragma CPP_Constructor ([Entity =>] {LOCAL_NAME})`
97 This pragma identifies an imported function (imported in the usual way
98 with pragma ``Import``) as corresponding to a C++ constructor.
99
100 A few restrictions are placed on the use of the ``Access`` attribute
101 in conjunction with subprograms subject to convention ``CPP``: the
102 attribute may be used neither on primitive operations of a tagged
103 record type with convention ``CPP``, imported or not, nor on
104 subprograms imported with pragma ``CPP_Constructor``.
105
106 In addition, C++ exceptions are propagated and can be handled in an
107 ``others`` choice of an exception handler. The corresponding Ada
108 occurrence has no message, and the simple name of the exception identity
109 contains ``Foreign_Exception``. Finalization and awaiting dependent
110 tasks works properly when such foreign exceptions are propagated.
111
112 It is also possible to import a C++ exception using the following syntax:
113
114
115 ::
116
117 LOCAL_NAME : exception;
118 pragma Import (Cpp,
119 [Entity =>] LOCAL_NAME,
120 [External_Name =>] static_string_EXPRESSION);
121
122
123 The ``External_Name`` is the name of the C++ RTTI symbol. You can then
124 cover a specific C++ exception in an exception handler. If the string
125 ends with "'Class", as if referencing the Class attribute of the C++
126 type, that enables "class-wide" type matching, i.e., instances of C++
127 classes derived from the one denoted by the RTTI symbol, that would be
128 caught by C++ handlers for that type, will also be caught by Ada
129 handlers for ``Entity``. For non-class-wide RTTI symbols imported from
130 C++, only exact type matches will be handled. C++ rethrown (dependent)
131 exceptions are not distinguishable from the corresponding primary
132 exceptions: they are handled exactly as if the primary exception had
133 been raised.
134
135 With imported exceptions, especially with base-type matching, a single
136 handled_sequence_of_statements may have exception handlers with
137 choices that cover the same C++ types in ways that GNAT cannot detect.
138 For example, C++ classes ``base`` and ``derived`` may be imported as
139 exceptions with base-type matching, but GNAT does not know that they
140 are related by inheritance, only the runtime will know it. Given:
141
142 ::
143
144 exception
145 when Derived_Exception => null;
146 when Base_Exception => null;
147 when others => null;
148
149 the earliest handler that matches the type of the raised object will
150 be selected. If an instance of ``derived`` or a further derived type
151 is raised, the first handler will be used; if an instance of ``base``
152 that is not an instance of ``derived`` is raised, the second handler
153 will be used; raised objects that are not instances of ``base`` will
154 be handled by the ``others`` handler. However, if the handlers were
155 reordered (``others`` must remain last), the ``Derived_Exception``
156 handler would never be used, because ``Base_Exception`` would match
157 any instances of ``derived`` before ``Derived_Exception`` or
158 ``others`` handlers were considered. Mixing exact-type and base-type
159 matching exceptions may also involve overlapping handlers that GNAT
160 will not reject: an exact-type ``Base_Only_Exception`` handler placed
161 before ``Base_Exception`` will handle instances of ``base``, whereas
162 instances of derived types will be handled by
163 ``Base_Exception``. Swapping them will cause ``Base_Exception`` to
164 handle all instances of ``base`` and derived types, so that a
165 subsequent handler for ``Base_Only_Exception`` will never be selected.
166
167 The C++ object associated with a C++ ``Exception_Occurrence`` may be
168 obtained by calling the ``GNAT.CPP_Exceptions.Get_Object_Address``
169 function. There are convenience generic wrappers named ``Get_Object``,
170 ``Get_Access_To_Object``, and ``Get_Access_To_Tagged_Object``,
171 parameterized on the expected Ada type. Note that, for exceptions
172 imported from C++, the address of the object is that of the subobject
173 of the type associated with the exception, which may have a different
174 address from that of the full object; for C++ exceptions handled by
175 ``others`` handlers, however, the address of the full object is
176 returned.
177
178 E.g., if the imported exception uses the RTTI symbol for the base
179 class, followed by "'Class", and the C++ code raises (throws) an
180 instance of a derived class, a handler for that imported exception
181 will catch this ``Exception_Occurrence``, and ``Get_Object_Address``
182 will return the address of the base subobject of the raised derived
183 object; ``Get_Object``, ``Get_Access_To_Object`` and
184 ``Get_Access_To_Tagged_Object`` only convert that address to the
185 parameterized type, so the specified type ought to be a type that
186 imports the C++ type whose RTTI symbol was named in the declared
187 exception, i.e., base, not derived or any other type. GNAT cannot
188 detect or report if a type is named that does not match the handler's
189 RTTI-specified type.
190
191 For ``others`` handlers, and for exact type matches, the full object
192 is obtained. The ``Get_Type_Info`` function that takes an
193 ``Exception_Occurrence`` argument can be used to verify the type of
194 the C++ object raised as an exception. The other ``Get_Type_Info``
195 function, that takes an ``Exception_Id``, obtains the type expected by
196 the handler, and no such type exists for ``others`` handlers.
197 ``GNAT.CPP.Std.Name`` can then convert the opaque
198 ``GNAT.CPP.Std.Type_Info_Ptr`` access to ``std::type_info`` objects,
199 returned by either ``Get_Type_Info`` function, to a C++ mangled type
200 name.
201
202 If an ``Exception_Occurrence`` was raised from C++, or following C++
203 conventions, ``GNAT.Exception_Actions.Exception_Language`` will return
204 ``EL_Cpp``, whether the exception handler is an imported C++ exception
205 or ``others``. ``GNAT.Exception_Actions.Is_Foreign_Exception`` returns
206 True for all of these, as well as for any case in which
207 ``Exception_Language`` is not ``EL_Ada``.
208
209 ::
210
211 -- Given the following partial package specification:
212
213 Base_Exception : exception;
214 pragma Import (Cpp, Base_Exception, "_ZTI4base'Class");
215 -- Handle instances of base, and of subclasses.
216
217 type Base is limited tagged record
218 [...]
219 end record;
220 pragma Import (Cpp, Base);
221
222 type Derived is limited tagged record
223 [...]
224 end record;
225 pragma Import (Cpp, Derived);
226
227 type Unrelated is access procedure (B : Boolean);
228
229 function Get_Base_Obj_Acc is
230 new Get_Access_To_Tagged_Object (Base);
231 function Get_Derived_Obj_Acc is
232 new Get_Access_To_Tagged_Object (Derived);
233 function Get_Unrelated_Obj_Acc is
234 new Get_Access_To_Object (Unrelated);
235
236 procedure Raise_Derived;
237 -- Raises an instance of derived (with a base subobject).
238
239
240 -- The comments next to each statement indicate the behavior of
241 -- the following pseudocode blocks:
242
243 begin
244 Raise_Derived;
245 exception
246 when BEx : Base_Exception =>
247 ?? := Is_Foreign_Exception (BEx); -- True
248 ?? := Exception_Language (BEx); -- EL_Cpp
249 ?? := Name (Get_Type_Info (BEx)); -- "7derived"
250 ?? := Name (Get_Type_Info (Exception_Identity (BEx))); -- "4base"
251 ?? := Get_Object_Address (BEx); -- base subobject in derived object
252 ?? := Get_Base_Obj_Acc (BEx): -- ditto, as access to Base
253 ?? := Get_Derived_Obj_Acc (BEx): -- ditto, NO ERROR DETECTED!
254 ?? := Get_Unrelated_Obj_Acc (BEx): -- ditto, NO ERROR DETECTED!
255 end;
256
257
258 begin
259 Raise_Derived;
260 exception
261 when BEx : others =>
262 ?? := Is_Foreign_Exception (BEx); -- True
263 ?? := Exception_Language (BEx); -- EL_Cpp
264 ?? := Name (Get_Type_Info (BEx)); -- "7derived"
265 ?? := Get_Type_Info (Exception_Identity (BEx)); -- null
266 ?? := Get_Object_Address (BEx); -- full derived object
267 ?? := Get_Derived_Obj_Acc (BEx): -- ditto, as access to Derived
268 ?? := Get_Base_Obj_Acc (BEx): -- ditto, NO ERROR DETECTED!
269 ?? := Get_Unrelated_Obj_Acc (BEx): -- ditto, NO ERROR DETECTED!
270 end;
271
272 The calls marked with ``NO ERROR DETECTED!`` will compile sucessfully,
273 even though the types specified in the specializations of the generic
274 function do not match the type of the exception object that the
275 function is expected to return. Mismatches between derived and base
276 types are particularly relevant because they will appear to work as
277 long as there isn't any offset between pointers to these types. This
278 may hold in many cases, but is subject to change with various possible
279 changes to the derived class.
280
281 The ``GNAT.CPP.Std`` package offers interfaces corresponding to the
282 C++ standard type ``std::type_info``. Function ``To_Type_Info_Ptr``
283 builds an opaque ``Type_Info_Ptr`` to reference a ``std::type_info``
284 object at a given ``System.Address``.
285
286
287 .. _Interfacing_to_COBOL:
288
289 Interfacing to COBOL
290 ====================
291
292 Interfacing to COBOL is achieved as described in section B.4 of
293 the Ada Reference Manual.
294
295 .. _Interfacing_to_Fortran:
296
297 Interfacing to Fortran
298 ======================
299
300 Interfacing to Fortran is achieved as described in section B.5 of the
301 Ada Reference Manual. The pragma ``Convention Fortran``, applied to a
302 multi-dimensional array causes the array to be stored in column-major
303 order as required for convenient interface to Fortran.
304
305 .. _Interfacing_to_non-GNAT_Ada_code:
306
307 Interfacing to non-GNAT Ada code
308 ================================
309
310 It is possible to specify the convention ``Ada`` in a pragma
311 ``Import`` or pragma ``Export``. However this refers to
312 the calling conventions used by GNAT, which may or may not be
313 similar enough to those used by some other Ada 83 / Ada 95 / Ada 2005
314 compiler to allow interoperation.
315
316 If arguments types are kept simple, and if the foreign compiler generally
317 follows system calling conventions, then it may be possible to integrate
318 files compiled by other Ada compilers, provided that the elaboration
319 issues are adequately addressed (for example by eliminating the
320 need for any load time elaboration).
321
322 In particular, GNAT running on VMS is designed to
323 be highly compatible with the DEC Ada 83 compiler, so this is one
324 case in which it is possible to import foreign units of this type,
325 provided that the data items passed are restricted to simple scalar
326 values or simple record types without variants, or simple array
327 types with fixed bounds.