comp.lang.ada
 help / color / mirror / Atom feed
From: Samuel Tardieu <sam@rfc1149.net>
Subject: Re: Interfacing to C without dynamic memory
Date: Sat, 15 Nov 2008 12:52:54 +0100
Date: 2008-11-15T12:55:02+01:00	[thread overview]
Message-ID: <87bpwhurxl.fsf@willow.rfc1149.net> (raw)
In-Reply-To: wcczlk1vr2g.fsf@shell01.TheWorld.com

>>>>> "Bob" == Robert A Duff <bobduff@shell01.TheWorld.com> writes:

Bob> Makes sense.  You could write a C program that #include's the
Bob> relevant .h file, and prints out an Ada package spec containing
Bob> the above Ada code.  You could run this as part of your build
Bob> scripts.

Doing it properly is quite painful when you cross-compile, you have to
play dirty unportable tricks such as parsing the assembly file output
by the compiler to extract the value. This is the way I originally did
it in GLADE, it was then used to generate GNAT.Sockets.Constants, but
as you know AdaCore recently switched to parsing the C compiler
output, which was possible because the GCC C compiler (native or
cross) is always available when building the runtime.

Note that you can also do it at run time, even if it costs a few more
cycles to allocate the object, by taking advantage of C ability to
resolve "sizeof" into a static value at compile time. This obliviates
the cross-compilation issues. Here is an example (t.c, t_interface.ads
and test.adb): (note that in real life, one would include the header
defining "struct T" instead of exporting "T_size" in the same file)

/* t.c */
#include <stdlib.h>
struct T {
  char a;
  void *b;
  short c;
  char d;
};
const size_t T_size = sizeof(struct T);

-- t_interface.ads
with Interfaces.C;
package T_Interface is

   T_Size : constant Interfaces.C.size_t;
   pragma Import (C, T_Size, "T_size");

   type Opaque_T is new Interfaces.C.char_array (1 .. T_Size);
   for Opaque_T'Alignment use 8;

private

  pragma Linker_Options ("t.o");

end T_Interface;

-- test.adb
with Ada.Text_IO; use Ada.Text_IO;
with T_Interface; use T_Interface;

procedure Test is
   My_T : Opaque_T;
begin
   Put_Line ("Size of T in bits:" & My_T'Size'Img);
end Test;



  reply	other threads:[~2008-11-15 11:52 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2008-11-14 13:58 Interfacing to C without dynamic memory Maciej Sobczak
2008-11-14 20:35 ` Damien Carbonne
2008-11-15  1:12   ` Randy Brukardt
2008-11-14 23:13 ` Robert A Duff
2008-11-15 11:52   ` Samuel Tardieu [this message]
2008-11-16 21:31     ` Maciej Sobczak
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox