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.
The following is the C routine:
#include <stdio.h>
char c_str[13];
void c_print_str() { printf ("Now in C routine called from Pascal code.\n"); printf ("string is %s.\n", c_str); fflush (stdout); /* So the text really appears now. */ }
The following is the pascal program:
program str_trans(input);
(* This is an attempt to pass a string from a pascal program to a c function. The corresponding c code is in str_trans.c It is compiled with gpc --automake --unit-path=/home/x/pas str_trans.pas -o str_trans *)
{$L str_trans.c} {$X+}
procedure c_print_str; asmname 'c_print_str';
var char_ptr: ^char; c_str: cstring; asmname 'c_str'; external;
begin
new( char_ptr ); char_ptr^ := 'x'; writeln( char_ptr^ ); flush( output );
c_str := char_ptr;
writeln( 'calling c function' ); c_print_str; end.
As shown, it ends up with garbage in c_str. If I change the value of char_ptr^, the garbage changes.
If I try simple assignment in the pascal program, such as c_str := 'x'; or c_str[3] := 'x'; or c_str^ := char_ptr^ it compiles ok, but generates run-time segmentation errors.
So, the ideal help would be if someone could explain to me how to assign to c_str. If not, does anyone know how to pass string data between C and Pascal programs in some other manner?
Thanks, and happy solstace to all! HB