Assignment of cstrings passed to C routine

Prof A Olowofoyeku (The African Chief) chiefsoft at bigfoot.com
Sat Dec 22 23:01:22 CET 2007


On 22 Dec 2007 at 12:02, Harmonious Botch  wrote:

> 
> I'm trying to call a C routine from a pascal program, and pass string data
> back and forth.  I can call it, I can pass integers back and forth ( thanks
> to Frank H ), but I can't pass strings.  Attempts to assign data to a
> cstring either result in segmentation errors or garbage in the string.
[...]
Your code is all wrong.

This is a better version of your Pascal program;

program str_trans(input);

uses strings; { non standard - but if you will use C strings, then you 
will need some of the routines exported by this unit - or you will need to 
write them yourself }

{$L str_trans.c}
{$X+}

procedure c_print_str; external name 'c_print_str';
var 
  char_ptr: cstring;
  c_str: array [0..12] of char; external name 'c_str'; 
begin
  char_ptr := strnew ('x and y');
  writeln( char_ptr );
  strcopy (c_str, char_ptr);
  writeln( 'calling c function' );
  c_print_str;  
  strdispose (char_ptr);
end.

However, a better way (IMHO) than using global variables in your C program 
is for the C function to take a string parameter, and then pass a cstring 
to it in your Pascal program. You need to know the size of the buffer of 
the string being passed (e.g., an integer parameter can be used for this 
), and you also need to decide who "owns" the pointer for subsequent 
disposal.

Best regards, The Chief
--------
Prof. Abimbola A. Olowofoyeku (The African Chief) 
web:  http://www.greatchief.plus.com/






More information about the Gpc mailing list