From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-0.3 required=5.0 tests=BAYES_00, REPLYTO_WITHOUT_TO_CC autolearn=no autolearn_force=no version=3.4.4 Path: buffer2.nntp.dca1.giganews.com!border2.nntp.dca1.giganews.com!border1.nntp.dca1.giganews.com!nntp.giganews.com!usenet.blueworldhosting.com!feeder01.blueworldhosting.com!feeder.erje.net!1.eu.feeder.erje.net!news.fcku.it!aioe.org!.POSTED!not-for-mail From: "Dmitry A. Kazakov" Newsgroups: comp.lang.ada Subject: Re: Returning a string from C Date: Thu, 23 Jul 2015 09:17:54 +0200 Organization: cbb software GmbH Message-ID: References: <27cd219d-fff7-4c2a-90c7-ec10a917b4cb@googlegroups.com> Reply-To: mailbox@dmitry-kazakov.de NNTP-Posting-Host: 5ZS5s7Q3rAN7MBP/UXLPIQ.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: 40tude_Dialog/2.0.15.1 X-Notice: Filtered by postfilter v. 0.8.2 Xref: number.nntp.giganews.com comp.lang.ada:194310 Date: 2015-07-23T09:17:54+02:00 List-Id: 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