
Is there a way in the foreign function interface to pass to a function a struct by value? I explain it better. There are two ways in c to pass structs, as in the following example: /* begin c code */ struct couple{ int a; int b; }; //by value int print_couple (struct couple cpl) { printf("%d\n", cpl.a); printf("%d\n", cpl.b); return(0); } //by address int print_couple_ptr (struct couple *cpl) { printf("%d\n", cpl->a); printf("%d\n", cpl->b); return(0); } /* end c code */ Apparently in the ffi it is possible to import the second version, as: foreign import ccall "print_couple_ptr" printCouple::Ptr Couple->IO Int But not the first, as a struct it's not an atomic type. So how does one solve this issue? Cheers, Federico

On Jan 30, 2008 5:16 AM, Federico Squartini
foreign import ccall "print_couple_ptr" printCouple::Ptr Couple->IO Int
But not the first, as a struct it's not an atomic type. So how does one solve this issue?
(This applies to x86-64 only!) In the case of your struct couple, I believe that it's small enough that it will be passed in registers: http://www.x86-64.org/documentation/abi.pdf
1. If the size of an object is larger than two eightbytes, or it contains unaligned fields, it has class MEMORY.
However, it's larger than this the C compiler will actually call memcpy to make a copy before calling the function with a pointer to the copy on the parent's stack. With the Haskell FFI, the portable solution is probably to write a very simple wrapper .c file which takes a pointer and calls the real function with the contents of that pointer. Then you just call your wrapper function. You can make these functions by the dozen with the preprocessor. AGL -- Adam Langley agl@imperialviolet.org http://www.imperialviolet.org 650-283-9641
participants (2)
-
Adam Langley
-
Federico Squartini