On 22 Nov 2003 at 2:18, Frank Heckenbach wrote:
Dr Christian Hicks wrote:
I am now trying to pass a string as well as an integer between C and Pascal. I am getting a segmentation fault.
As I wrote:
: However, for `const char *', do not use : `protected var Foo: CString' (because `CString' is already a pointer : so it would pass a pointer to a pointer), but simply `CString'.
That is not the only problem. Who owns the memory for the CString "s"? and who is allocating memory for it? Things are being copied to this variable without first having allocated any memory to it. This will work:
program pascalcallsC(input,output);
procedure world; external name 'world'; procedure w1(var i : integer; s : cstring); external name 'c_w1';
var i : integer; s : cstring; begin writeln("Hello world from Pascal"); world; writeln("Returned from C to Pascal\n"); i := 96; getmem (s, 260); { ahem - we need to allocate memory } w1(i,s); writeln("Returned from C again I = ",i); writeln("Return from C cstring = ",s); getmem (s, 260); { free this here, else memory leak on next line } s := "This is a CString"; { not really a good idea, IMHO } writeln("Trying out pascal ",s); end.
BTW: this is why is personally prefer "PChar" to "CString", because "PChar" seems to make it more obvious (at least to someone who is not very familiar with how strings work in C) that we are dealing with a pointer.
Best regards, The Chief -------- Prof. Abimbola A. Olowofoyeku (The African Chief) web: http://www.bigfoot.com/~african_chief/