Talk:Use another language to call a function: Difference between revisions

(→‎C code is wrong: new section)
Line 4:
==Task needs work/splitting?==
While writing the Tcl implementation, it occurred to me that a number of languages might want to deal with the cases where a parameter is an ‘in’ parameter differently from the case given (really a single ‘out’ parameter, plus a bit of metadata to describe the buffer size). No time to work on this now though. —[[User:Dkf|Donal Fellows]] 13:10, 18 August 2009 (UTC)
 
== C code is wrong ==
 
<lang c>#include <stdio.h>
 
extern int Query (char * Data, size_t * Length);
 
int main (int argc, char * argv [])
{
char Buffer [1024];
unsigned Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}</lang>
 
<lang c>#include <stdio.h>
 
int Query (char * Data, size_t * Length)
{
printf("Length = %zu, 0x%zx\n", *Length, *Length);
return 0;
}</lang>
 
<pre>$ cc -v
Reading specs from /usr/lib/gcc-lib/amd64-unknown-openbsd4.8/4.2.1/specs
Target: amd64-unknown-openbsd4.8
Configured with: OpenBSD/amd64 system compiler
Thread model: posix
gcc version 4.2.1 20070719
$ cc -o main main.c query.c
main.c: In function 'main':
main.c:10: warning: passing argument 2 of 'Query' from incompatible pointer type
$ ./main
Length = 7971459302400, 0x74000000400
failed to call Query</pre>
 
It should say 'Length = 1024', not 'Length = 7971459302400'. The problem is that main() passed an <tt>unsigned *</tt> but Query() expects <tt>size_t *</tt>. On my machine, <tt>unsigned</tt> is 4 bytes but <tt>size_t</tt> is 8 bytes.
 
I would like to fix the C code (by changing <tt>unsigned Size</tt> to <tt>size_t Size</tt>, and while there, by adding to main() some return statements), but I worry that if I fix the C code, then I will destroy all the examples that use the old C code. --[[User:Kernigh|Kernigh]] 15:45, 12 February 2011 (UTC)
Anonymous user