From: Martin Krischik <krischik@users.sourceforge.net>
Subject: Re: C bindings, Interfaces.C.Pointers etc.
Date: Thu, 13 May 2004 19:37:14 +0200
Date: 2004-05-13T19:37:14+02:00 [thread overview]
Message-ID: <8969563.sTNc1ZJU4A@linux1.krischik.com> (raw)
In-Reply-To: pan.2004.05.13.15.56.14.678895@linuxchip.demon.co.uk.uk.uk
Dr. Adrian Wrigley wrote:
> Thanks Martin for this suggestion.
>
> I have given (aninvolvedimation of) my code below.
>
> It doesn't use the I.C.Pointers package, and allows
> Ada programs to access elements of the arrays using
> standard array notation. The main problem is that
> the bound Ada uses are over-sized, and simple use
> of 'range and 'last will fall off the ends.
There is one more way but only usable when you C and Ada compiler use the
same memory layout for variables. The example works for Strings:
type C_Array is array (Natural range <>) of aliased Character;
for C_Array'Component_Size use Interfaces.C.char'Size;
pragma Convention (
Convention => C,
Entity => C_Array);
package C_Pointers
is new
Interfaces.C.Pointers (
Index => Natural,
Element => Character,
Element_Array => C_Array,
Default_Terminator => Character'First);
type C_String
is record
-- Address of some C Array
Data : C_Pointers.Pointer;
-- Size of the Array.
Size : Interfaces.C.size_t;
end record;
Ada_String : String (1 .. Natural (Some_C_String.Size));
for Ada_String 'Address use Some_C_String.Data.all'Address;
The trick is in the last line. This is of corse an Unchecked_Convertion
without actually moving the Data. Use at your own risk.
You can probably reduce the code involved by using an normal access to
Character for C_String.Data.
> Overall this solution meets my needs very well, and
> if I accidentally use the invalid array (upper) bound,
> the program crashes very rapidly (like it would have
> done in C with a similar bug!).
With the trick above Ada will check the array bounds - when Size containts
the right value.
> I'm a little surprised that I.C.Pointers doesn't seem
> to provide a convenient and efficient solution to this
> problem - using C pointers directly in array access.
I.C.Pointers is supposed to all the checked convertions needed and will work
when C and Ada use different memory layout - at least that's the theorie.
With Regards
Martin.
--
mailto://krischik@users.sourceforge.net
http://www.ada.krischik.com
next prev parent reply other threads:[~2004-05-13 17:37 UTC|newest]
Thread overview: 9+ messages / expand[flat|nested] mbox.gz Atom feed top
2004-05-11 13:14 C bindings, Interfaces.C.Pointers etc Dr. Adrian Wrigley
2004-05-11 18:17 ` tmoran
2004-05-11 18:48 ` Jeffrey Carter
2004-05-12 4:50 ` Simon Wright
2004-05-13 15:26 ` Dr. Adrian Wrigley
2004-05-12 6:30 ` Martin Krischik
2004-05-13 15:56 ` Dr. Adrian Wrigley
2004-05-13 17:37 ` Martin Krischik [this message]
2004-05-13 22:42 ` Jeffrey Carter
replies disabled
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox