comp.lang.ada
 help / color / mirror / Atom feed
From: "Dmitry A. Kazakov" <mailbox@dmitry-kazakov.de>
Subject: Re: Returning a string from C
Date: Thu, 23 Jul 2015 09:17:54 +0200
Date: 2015-07-23T09:17:54+02:00	[thread overview]
Message-ID: <svrr8jeuj5gn$.16vmrvatwo7mk$.dlg@40tude.net> (raw)
In-Reply-To: 27cd219d-fff7-4c2a-90c7-ec10a917b4cb@googlegroups.com

On Wed, 22 Jul 2015 19:20:34 -0700 (PDT), NiGHTS wrote:

> I am having some difficulty with returning a string from a C function.
> 
> Say I have the following C function:
> 
>     void Return_Hello (char *inout_Test_String ) {
>         strcpy( inout_Test_String, "Hello World" );
>     }

[...]

> What am I doing wrong here?

When you pass a string to C, use To_C from Interfaces.C that returns
char_array

 When you receive a string from C, use Chars_Ptr and Value from
Interfaces.C.Strings. E.g.

   function Foo (Text : String) return String is
      function Internal (S : char_array) return Chars_Ptr;
      pragma Import (C, Internal, "c_stuff");
      Result : Chars_Ptr;
   begin
      Result := Internal (To_C (Text));
      if Result /= Null_Ptr then
         return Value (Result);
      else
         return "";
      end if;
   end Foo;

When C side allocates a new string and your side is responsible for
deallocating it, use Free on Chars_Ptr from Interfaces.C.Strings.

If you want in-place string modified by C, pass char_array, maximum size,
actual length to C.

Never ever use strcpy, always strncpy.

-- 
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de


      parent reply	other threads:[~2015-07-23  7:17 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
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 [this message]
replies disabled

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