comp.lang.ada
 help / color / mirror / Atom feed
From: "Jeffrey R. Carter" <spam.jrcarter.not@spam.not.acm.org>
Subject: Re: Returning a string from C
Date: Wed, 22 Jul 2015 21:48:23 -0700
Date: 2015-07-22T21:48:23-07:00	[thread overview]
Message-ID: <moprjs$7oq$1@dont-email.me> (raw)
In-Reply-To: <27cd219d-fff7-4c2a-90c7-ec10a917b4cb@googlegroups.com>

On 07/22/2015 07:20 PM, NiGHTS wrote:
> 
> Say I have the following C function:
> 
>     void Return_Hello (char *inout_Test_String ) {
>         strcpy( inout_Test_String, "Hello World" );
>     }
> 
> This function will use the string memory generated on the Ada side and return a simple string "Hello World". Here is how I would interface with it:
> 
>     procedure Return_Hello ( Test_String : in out chars_ptr );
>     pragma Import (C, Return_Hello, "Return_Hello");
> 
> And this is how I would use it.
> 
>     use Interfaces.C;
>     use Interfaces.C.Strings;
> 
>     declare
> 
>         Test_String      : String (1 .. 100);
>         Test_String_Char : chars_ptr := New_String (Test_String);
> 
>     begin
>     
>         Return_Hello ( Test_String_Char );
>         Test_String := Value ( Test_String_Char ) ;
>         Ada.Text_IO.Put_Line ( Test_String );
>         Free (Test_String_Char);
>   
>     end;
> 
> When I run the program I get a runtime error "length check failed" on the line "Test_String := Value ( Test_String_Char );".
> 
> What am I doing wrong here?

Well, for one thing, you're thinking like a C person and using unnecessary
pointers. I'd import the procedure as

procedure Return_Hello (Test_String : out Char_Array);

and call it with

Test_String : Char_Array (1 .. 100);

Return_Hello (Test_String => Test_String);
Ada.Text_IO.Put_Line (Item => To_Ada (Test_String) );

As for the exception you get, Value returns the string pointed to by Item up to
but not including the terminating NUL, which is 11 characters. Test_String is
100 characters, so the lengths don't match.

-- 
Jeff Carter
"Sir Robin the not-quite-so-brave-as-Sir-Lancelot,
who had nearly fought the Dragon of Angnor,
who nearly stood up to the vicious Chicken of Bristol,
and who had personally wet himself at the
Battle of Badon Hill."
Monty Python & the Holy Grail
68


  reply	other threads:[~2015-07-23  4:48 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2015-07-23  2:20 Returning a string from C NiGHTS
2015-07-23  4:48 ` Jeffrey R. Carter [this message]
2015-07-23  4:54 ` Per Sandberg
2015-07-23  4:58 ` Laurent
2015-07-23  6:41 ` Pascal Obry
2015-07-23  7:17 ` Dmitry A. Kazakov
replies disabled

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