Ada 004 - Lesson 2 - Ada and C
Summary
TLDRThis ADA University lecture delves into mixed language programming, focusing on integrating Ada with C. It covers Ada's unique features for interfacing with foreign languages, as outlined in the 2012 ISO standard. The lecture includes examples of importing and exporting subprograms and memory objects between Ada and C, utilizing the 'Interfaces.C' package for scalars, strings, and pointers. It also addresses potential issues with elaboration and the use of pragmas for generating import statements from C headers. A quiz tests understanding of these concepts, aiming to solidify the knowledge imparted throughout the lecture.
Takeaways
- đ The ADA programming language has unique features for interfacing with foreign languages, including C, as part of its ISO standard 8652 revision 2012.
- đ The lecture covers the application of Ada's import/export aspects, link name, and external name in mixed language programming with C.
- đ It is recommended to start from the first lecture of the series for a comprehensive understanding of Ada and C mixed language programming.
- đ The 'Interfaces.C' package is vital for interfacing Ada with C, providing basic types, constants, and subprograms for scalar and string data passing.
- đ The 'Interfaces.C.Strings' package allows Ada programs to work with C-style strings, offering type-safe operations and conversions.
- đ Ada can import C function pointers and use them as access to subprogram entities, demonstrating interoperability between the two languages.
- đ The 'Interfaces.C.Pointers' package facilitates C-style pointer operations in Ada, including pointer arithmetic and array handling.
- đ ïž The GCC compiler can generate Ada specifications from C header files using the '-Fdump-ada-spec' flag, simplifying the integration process.
- đ Ada requires elaboration before accessing exported entities in a C main program, ensuring proper initialization and finalization.
- đ The quiz section of the lecture tests understanding of key concepts, such as importing/exporting subprograms, handling memory objects, and using Ada types with C pointers.
- đ The lecture concludes with a quiz to reinforce learning, emphasizing the practical application of Ada's features for interfacing with C.
Q & A
What is the main subject of the lecture series from ADA University?
-The main subject of the lecture series is mixed language programming with Ada and C, focusing on the features of the Ada programming language that support integration with the C programming language.
What is the purpose of the 'convention' aspect in Ada when interfacing with C?
-The 'convention' aspect in Ada is used to specify the calling convention of a subprogram when interfacing with C, ensuring that the Ada program correctly calls C functions using the appropriate calling conventions.
What is the role of the 'external name' aspect in Ada when importing a C subprogram?
-The 'external name' aspect is used to identify the name of the subprogram in the C source code, allowing Ada to correctly reference the C function despite any naming differences between the two languages.
How can a C subprogram be imported into an Ada program?
-A C subprogram can be imported into an Ada program by declaring it with the 'Import' aspect and specifying the 'External Name' aspect to match the name of the C function. The Ada main program can then call this imported function using an Ada entity identifier.
What is the purpose of the 'Interfaces.C' package in Ada?
-The 'Interfaces.C' package in Ada provides basic types, constants, and subprograms that allow an Ada program to pass scalars and strings to C functions. It includes types that resemble C types, facilitating the interfacing between Ada and C.
Why is the 'Interfaces.C.Strings' package useful in Ada?
-The 'Interfaces.C.Strings' package is useful because it allows an Ada program to allocate, reference, update, and free C-style strings. It provides types and subprograms for working with C strings in an Ada program, ensuring type safety and ease of use.
What is the significance of the 'Interfaces.C.Pointers' package in Ada?
-The 'Interfaces.C.Pointers' package is significant because it allows the Ada programmer to perform C-style operations on pointers. It includes an access type pointer that is C-compatible and provides functions for pointer arithmetic and copying.
What is the issue that may arise when using a C main program with exported Ada entities that require elaboration?
-An issue that may arise is that the Ada elaboration code, which performs explicit initialization of exported entities, must be executed by the C main program before accessing the exported entities. This is done by calling an external function called 'Ada_Init'.
How can Ada generate import pragmas for entities defined in C header files?
-Ada can generate import pragmas for entities defined in C header files by using the GCC compiler with the '-Fdump-ada-spec' flag along with the name of the C header file. This generates an Ada package specification that imports the functions from the C header.
What is the importance of calling 'Ada_Final' in a C main program?
-The call to 'Ada_Final' is important in a C main program to ensure that all Ada finalization code is executed upon completion of the program. This is necessary for proper resource cleanup and adherence to Ada's deterministic finalization properties.
What is the recommended approach for handling C strings in Ada?
-The recommended approach for handling C strings in Ada is to use the 'Interfaces.C.Strings' package, which provides type-safe subprograms for converting C string pointers into Ada strings, ensuring proper memory management and avoiding potential runtime errors.
Outlines
đ Introduction to Mixed Language Programming
In this lecture, Martin Pike introduces the ADA University course on mixed language programming with Ada and C. The lecture covers the features of the Ada programming language that support integration with C, including conventions, import/export aspects, and external names. He emphasizes the importance of starting from the beginning of the lecture series for a comprehensive understanding. The lecture will explore how to mix Ada and C, the use of interface child packages, and how to create main programs in either language that utilize foreign subprograms.
đ Importing C Subprograms into Ada
This section demonstrates how to import a subprogram implemented in C into an Ada main program. It explains the use of the 'external name' aspect to link the subprogram in the C source code with the Ada main program. An example is provided where an Ada program calls a C function that returns the value 10. Additionally, it discusses importing memory objects from C into Ada using conventions and external names, with a focus on type compatibility between Ada and C.
đ€ Exporting Ada Subprograms to C
This paragraph covers exporting Ada subprograms to be used in a C main program. It highlights the similarities between imported and exported subprograms, with the main difference being the use of the export aspect. Examples are provided showing the declaration of exported Ada subprograms and their implementation. It also demonstrates exporting Ada entities, such as constant memory objects, to C programs and how these entities are used in C code.
đŠ Interfaces and Child Packages
This part explains the package 'interfaces.C,' which provides basic types, constants, and subprograms for Ada to interface with C. It encourages studying this package in detail. Two child packages related to C pointers and strings are introduced. Examples include importing arrays of memory objects from C into Ada and converting C strings to Ada strings using the 'interfaces.C.strings' package. The use of these packages simplifies the integration of Ada with C functions and data structures.
đ Advanced Mixed Language Programming Techniques
Advanced techniques for mixed language programming are discussed, including the use of C function pointers in Ada. The paragraph provides examples of declaring function pointers in C and importing them into Ada as access-to-subprogram types. It also addresses the elaboration issues when using a C main program with exported Ada entities, emphasizing the need for calling 'ada_init' and 'ada_final' functions in the C program. The utility of automatic import pragma generation from C header files using GCC is also highlighted.
𧩠Quiz and Practical Applications
The final section of the lecture transitions to a quiz designed to test the understanding of the topics covered. It presents multiple-choice and code-correctness questions, focusing on importing and exporting subprograms, handling memory objects, and mixing Ada and C pointers. Each question is accompanied by an explanation of the correct answer, reinforcing key concepts. The lecture concludes by encouraging students to continue learning through other lectures in the course.
Mindmap
Keywords
đĄAda Programming Language
đĄC Programming Language
đĄConvention
đĄImport/Export
đĄExternal Name
đĄInterfaces.C
đĄSubprogram
đĄMemory Objects
đĄInterfaces.C.Strings
đĄInterfaces.C.Pointers
Highlights
Introduction to a lecture series on mixed language programming with Ada and C.
Unique features of Ada for interfacing with foreign languages as part of ISO standard 8652 revision 2012.
The importance of understanding Ada aspects involved in Ada and C mixed language programming.
Explanation of Ada's convention, import/export, link name, and external name for interfacing with C.
Demonstration of importing a C subprogram into an Ada program using the C calling convention.
How to import memory objects from C into Ada using Ada types from the interfaces package.
Exporting Ada subprograms and constants to a C main program with different entity names for external references.
The role of the 'interfaces' package in Ada for interfacing with C basic types, constants, and subprograms.
Details of 'interfaces.C' package for working with C pointers and strings in Ada.
Importing and exporting Ada and C strings using the 'interfaces.C.strings' package.
Using the 'interfaces.C.pointers' package for C-style pointer operations in Ada.
Importing C function pointers and using them as access to subprogram entities in Ada.
The necessity of calling 'Ada.Init' in a C main program before using exported Ada entities.
Automatic generation of import pragmas for C header files using the GCC compiler's '-F dump Ada spec' flag.
Quizzes to test understanding of Ada and C mixed language programming concepts.
Common issues and solutions when using C main programs with exported Ada entities that require elaboration.
The use of 'interfaces.T.strings' for type-safe handling of C strings in Ada.
Conclusion of the lecture with an invitation to continue learning Ada through other courses.
Transcripts
hello my name is Martin Pike and welcome
to this lecture from the ADA University
course on mixed language programming
with Ada and C the subject of this
lecture are the features of the ADA
programming language that provides
support for integration with the C
programming language together we shall
complete a series of slides and then you
will be assessed on your learning using
some quiz questions
the ADA programming language offers
unique features for interfacing to
foreign programming languages that are
part of amateur and progressive iso
standard 8 652 revision 2012 if you
haven't started at the beginning of this
lecture series I would strongly suggest
that you stop watching this lecture and
attend the first lecture in this series
it contains significant background
information that will greatly help with
learning this subject and from this
point onwards it is assumed you
understand the ADA aspects involved in
ADA and see mixed language programming
to recap they are convention
import/export link name and external
name
in this lecture we're going to cover how
these aspects are applied to mixing Ada
and C we're also going to cover the
interfaces child packages specific to
mixing Ada and C finally we'll look at
how you can have a main program in
either language and make use of forged
foreign language sub programs
we start off by looking at how a
subprogram implemented in c can be
imported into an a domain program the
example code shows an ADA main program
declaring a nested sub program that is
an imported function using the c calling
convention
the external name aspect has been used
to identify the name of the sub program
in the C source code the subsequent
fragment of C code shows the sub program
implementation that returns the numeric
value 10
the body code of the ADA main program
cause the imported C function using the
ADA entity identifier which causes the
value 10 to be output
it is also possible to import memory
objects from C as we can see in this
fragment of ADA code the familiar
Convention import and external named
aspects are used to specify the ADA
entity used to identify the foreign
language memory object in this case the
memory object is called the length and
it is defined in the subsequent snippet
of C code as being a constant size
underscore T typed value of 20
you will notice the use of an ADA type
from interfaces see that resembles the C
size underscores T type from the
standard Lib header file we will come on
to the details of interfaces see later
in this lecture but for now understand
its vital role in this subject the
output from the ADA main program would
be the value 20
exporting an ADA sub program to a C main
program it's just as simple as importing
a C sub program into ADA the exported
sub program entity looks very similar to
an imported sub program with the only
difference being a swapping off the
import aspect to the export aspect
of course there is a need for an
implementation of the exported sub
program in ada
here we show a package specification
containing the declaration of an
exported sub program and notably the ADA
entity name is different from the name
you used to reference it externally
there is a simple implementation in The
Associated package body that returns the
value 60
the example C main program here cause
this exported ADA sub program to print
out the value
in this example we export an ADA entity
to see that's a constant memory object
with a value 80
the same aspects have been used as when
exporting a subprogram but the external
name aspect has been altered in this
case to the length
on the seaside of the program the main
function again has to call ADA in it and
ADA final and then can make use of the
exported ADA entity the output from this
particular C main program would be the
value 80
you
the package interfaces dot C contains
the basic types constants and sub
programs that allow an ADA program to
pass scalars and strings to see
functions
the minimum number of types constants
and sub programs are provided to enable
interfacing to see foreign language
entities
the reader is encouraged to study the
contents of this package in detail
offline from the course as it contents
are very valuable to a programmer
interfaces see is the parent package of
two important child packages
related specifically to see pointers and
strings to areas where C and ADA differ
considerably
it is also possible to import a raise of
memory objects from C into ADA in this
example we see a piece of C code that
declares for size T typed memory objects
in an array this array is an imported
into an ADA entity that has been typed
using an ADA array declaration
the a demain program iterates over the
array printing out the hex version of
the C memory object
in this particular case the hex values
10 20 30 and 40 are output to the
console
the interfaces see dot strings package
is defined in the ADA programming
language reference manual as a package
declaring types and sub programs
allowing an ADA program to allocate
reference update and free c style
strings
in this example we see a snippet of C
code declaring a function that returns a
pointer to the string hello world the
AIDA
main program imports the c function as
an eider entity called getstring
the main program then goes on to use
features of the interfaces seeds or
strings package to convert the string
pointer into a suitable data access type
and subsequently accesses the target
object as an ADA string the ADA string
is then suitable for input into the ADA
textio put line sub program which will
produce the program's output of the
string hello world
exporting ADA strings to see main
programs can be made simpler by using
the interfaces dot C dot strings package
in this code example we see a set of
constant ADA strings being declared
using types from interfaces that cedar
strings the data structure is exported
using the sea Convention as the
externally named entity some strings the
C main program is able to access the
array of strings and iterate through
them printing them out until it finds a
null pointer please note the use of the
null underscore PTR constant from
interfaces c dot strings
the child generic package interfaces
cedar pointers allows the ADA programmer
to perform c-style operations on
pointers
it includes an access type pointer that
is C compatible and corresponds to one
use of C's element star
the generic allows two styles of usage
one in which the array is terminated by
a special terminating element and the
other in which the programmer needs to
keep track of the length
this is achieved by providing two
versions of a function called value that
dereferences a pointer and delivers the
designated array one provided with the
Terminator and the other
with the legs
the package also provides several
pointer arithmetic functions and copy
procedures that copy the contents of a
source pointer into the array designated
by a destination pointer if generics are
new to you then I would suggest you
visit the programming in the large
course from the ADA University where
they are covered by a dedicated lecture
ada can also import C function pointers
and use them as access to sub program
entities the C code declares a function
called C underscore function that
accepts a pointer to a size and score T
object that is eventually dereference as
an input to printf
the func function pointer is assigned
the address of this C underscore
function
the a domain program declares an access
to sub program type that matches the
signature of the C function pointer it
then imports the func entity from C and
D references the pointer to invoke the C
function that eventually outputs 10
using printf
you
in this slide we're going to deal with
an issue that may arise when using a C
main program and exported ADA entities
that require elaboration the example
code snippet shows an ADA package
specification exporting a memory object
that is explicitly initialized with the
result of calling the function f
the explicit initialization is performed
by the ADA elaboration code and this
must be executed by the C main program
before attempting to access the exported
entities the C main program must call an
external function called ADA in it to
execute the ADA elaboration code and if
this was admitted the C main program
would display a random value almost
certainly not 55
the sea main program must also call the
external function ADA final upon
completion to ensure all ADA
finalization code is also executed
the canals contain a very useful feature
for automatically generating import
pragmas for entities defined in c header
files
the example had a foul here called
Sealift H provides three function
prototypes with various return types and
parameters
it is possible to produce an ADA a
patent specification for this C header
file by passing a particular flag to the
GCC compiler the - F dump ADA spec flag
is passed to GCC along with the name of
the C header file the - capital C flag
is used to ensure comments from the C
header file are copied into the
generated ADA package specification
the resulting ADA package specification
for the example C header file is shown
at the bottom of this slide
each function has been imported as an
identity and appropriate data types have
been used for return values and
parameters note the use of interfaces T
dot strings for the character points a
return value from function 3
a time of writing a to 2005 pragmas are
generated but these could be manually
converted to a de 2012 aspects perhaps
in the future support for a tour 2012
aspects will be added
we've now reached the end of the slide
section of this lecture you should now
have enough knowledge of this subject to
complete a small quiz with questions
designed to test your understanding each
question is marked and you will have a
chance to review your score at the end
of the lecture good luck
question one kicks off with an example
of importing a C sub program into an ADA
main program the ADA entity get
underscore length is a function
represented by convention import and
external name aspects the ADA main
program body calls get length if you
think this code is correct then please
click the tick icon
otherwise click the line of code that is
incorrect
the answer is no the code is incorrect
and will fail to link into an executable
the external name string must match the
foreign language entity name exactly
including the use of the correct case
here we used the camel case string get
length in the Declaration of the ADA
entity for the imported C sub program
however the C code used all lowercase
for the Declaration of the get length
function
question 2 covers exporting an ADA sub
program for use by a C main program the
function get underscore length will
return the value 60 when called study
this code carefully if you think this
code is correct and please click the
check icon
otherwise click the area of the code
that is incorrect
the answer is no the code is incorrect
and will fail to execute correctly there
must be a call to aid in it before the
use of any exported identities by the C
main program
question three demonstrates the use of
an imported memory object using the C
convention the program declares an
identity using the name the underscore
length but specifies a different
external name for the entity in the
foreign language
the foreign language has declared the
memory object as a constant value 20
if you think this code is correct then
please click the tick icon otherwise
click the line of code that is incorrect
the answer is yes the code is correct
ada is able to use memory objects
imported from foreign languages without
having the responsibility for setting
their values
question four mixes the use of a to
access types with C pointers but without
using any pointer arithmetic when the C
program executes it intends to output
the number 50 the example code is much
larger than previous questions so please
take your time to read it through and
understand it if you think the code is
correct and please click the tick icon
otherwise click the line of code that is
incorrect
the answer is yes the code is correct it
is perfectly safe to mix ADA access
types with C pointers as long as the
types from interfaces dot C are used as
the target types
question 5 presents a method of
accessing an array of C constants
imported as an identity the body of the
a domain program iterates over the
imported entity until the value 9999 is
encountered again this code is quite
advanced so please take some time to
review it before attempting the question
of correctness if you think this code is
correct and please click the tick icon
otherwise click the line of code that is
incorrect
the answer is yes the code is correct
but it is not recommended to do this
kind of access type of manipulation
there are some big assumptions being
made by the code in the question slide
about the imported see data structure a
better solution is shown here it is
restricted to a single use of the tick
access attribute and is made type safe
by using this structure returned by the
value sub program from the interfaces
dot C dot points a package
it is probably debatable about which
solution is better but in the interests
of fairness both have been presented in
this lecture
question six is a multiple-choice
question and it poses the question which
of these packages is not part of the
hierarchy of packages rooted in
interfaces si please select your chosen
answer and then click Submit to see if
you are correct
the answer was interfaces see
sub-programs this is not part of the
interfaces c package hierarchy
question 7 asks what output will this a
demain program produce by using an
imported c string will it fail to
compile output the hello world string
will raise program error exception at
runtime make your selection and click
Submit to see if you are correct
the answer is the hello world strength
as you can see it's very easy to use see
strings
imported into ADA main programs
you
moving on to question eight we see an
ADA package specification exporting a
constant string using the C Convention
and the external name is ADA string the
C main program uses an externally
declared string entity called ADA string
in a call to printf
we'll the C main program failed to
compile enter an infinite loop and never
return or print the hello world string
make our selection and then click the
submit button to check your answer
the answer was the hello world strength
again this demonstrates how easy it is
to use strongly typed ADA string
declarations in a C main program with
this example you can see that declaring
all your C strings then ADA packages
helps introduce typesafe data structures
into your C programs
the penultimate question again asks to
identify what string output an aider
main program will produce here we use
data types from interfaces seed strings
to work with imported c functions that
use char star entities interfaces to c
dot strings provides various type safe
sub programs for working with c strings
what do you think the output from this
aida program will be will it be the
hello world string nothing due to a
program error exception at runtime
all well the code failed to compile in
the first place
select your answer and click the submit
button to see if you are correct
the answer is the hello world string
first the chart access array object
returned by the imported C function is
given to the to Charles pointer sub
program from interfaces dot C dot
strings the result of this sub program
is given two value from interfaces cedar
string which will return an ADA string
version of the character pointer this is
then permissible to be passed to the put
line operation from ADA textio
our final question continues the theme
of using interfaces seed of strings this
code declares a constant set of ADA
strings and exports them as the concei
convention entity called some strings
the C main program uses these strings in
a loop what do you think the output from
the C main program will be
will it be gibberish code or the ADA
code raises a constraint error exception
at runtime or the hello world string
select your answer and click the submit
button to see if you are correct
not surprisingly the answer was the
hello world string you could use this
type of constant aid of structure to
limit the need for error-prone C strings
and gain the type safety of ADA strings
that concludes the quiz please click the
continue button to review your score
congratulations you have completed this
lecture I hope you have found it a
valuable step in learning the ADA
programming language and that you
continue on to the other lectures in
this course from the ADA University
thank you
5.0 / 5 (0 votes)