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.7 required=5.0 tests=BAYES_00,INVALID_DATE, MSGID_SHORT,REPLYTO_WITHOUT_TO_CC autolearn=no autolearn_force=no version=3.4.4 Path: utzoo!attcan!uunet!software.org!blakemor From: blakemor@software.org (Alex Blakemore) Newsgroups: comp.lang.ada Subject: Re: C Strings in Ada? Message-ID: <1304@software.software.org> Date: 10 Jun 90 20:38:41 GMT References: <920024@hpclapd.HP.COM> <920025@hpclapd.HP.COM> Sender: news@software.org Reply-To: blakemor@software.org (Alex Blakemore) Organization: Software Productivity Consortium, Herndon, Virginia List-Id: In article <920025@hpclapd.HP.COM> defaria@hpclapd.HP.COM (Andy DeFaria) writes: >What is the best way to represent C_Strings in Ada? Dave Emery presented the following solution for some compilers. $$ procedure to_c (str : string) $$ is $$ procedure c_routine (addr : system.address); $$ pragma interface (C, c_routine); -- (void) c_routine(s) $$ -- char * s; $$ c_string : constant string := str & Ascii.NUL; $$ begin $$ c_routine(c_string(c_string'first)'address); $$ end to_c; $$ $$ function from_c $$ return string $$ is $$ function c_function $$ return System.address; $$ pragma interface (C, c_function); -- char * c_function $$ function strlen (addr : System.address) $$ return integer; $$ pragma interface (C, strlen); -- the C function of $$ -- the same name $$ addr_from_c : System.address; $$ begin $$ addr_from_c := c_function; $$ declare $$ answer : string(1..strlen(addr_from_c); $$ for answer'address use at addr_from_c; $$ begin $$ return answer; $$ end; $$ end from_c; Mr. DeFaria replied > I kinda agree with you that the "right" way to do this would be to keep Ada > strings as Ada strings and do the conversion in package but you have not > addressed one of my critical concerns: What about the overhead incurred by > having to call the heap manager to allocate a new string just to append > ASCII.NUL so that the C routine I'm calling will be able to handle it I dont think this solution *requires* heap allocation. A good compiler would be free to use stack space for the C strings in these cases, both for the local constant c_string and for the return value. Of course, there is the overhead of copying the strings but the allocation can be relatively cheap. ----------------------------------------------------------------------- Alex Blakemore Internet: blakemore@software.org Software Productivity Consortium UUNET: ...!uunet!software!blakemore 2214 Rock Hill Rd, Herndon VA 22070 Bellnet: (703) 742-7125