guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: dynamic ffi and C struct


From: Mark H Weaver
Subject: Re: dynamic ffi and C struct
Date: Sat, 19 May 2012 20:45:44 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.0.92 (gnu/linux)

cong gu <address@hidden> writes:
> Is it possible to use the current dynamic ffi to call a C function
> whose parameter is a C struct (not a pointer to a C struct) ?

Although it is not documented in the manual, I see from the source code
that a C struct parameter can be specified using a nested list in the
foreign type passed to 'pointer->procedure'.

> For example, what should I do for the following function?
>
> typedef struct {
>   int dat[2];
> } foo_t;
>
> int func ( foo_t arg );

For this example, there's an additional complication of the inline array
within the struct, which is not supported by libffi, upon which Guile's
dynamic FFI is based.  I'm not an expert on this subject, but I strongly
suspect that on most (if not all) platforms, the struct above has the
same layout as the following one:

  typedef struct {
    int dat_0;
    int dat_1;
  } foo_t;

Assuming this is the case, here's one way to wrap 'func':

  (use-modules (system foreign))

  (define foo-library-obj (dynamic-link "libfoo"))
  (define foo-struct-type (list int int))
  
  (define (make-foo-struct dat-0 dat-1)
    (make-c-struct foo-struct-type (list dat-0 dat-1)))
  
  (define func
    (pointer->procedure int
                        (dynamic-func "func" foo-library-obj)
                        (list foo-struct-type)))

and here's an example of how to use it:

  (func (make-foo-struct 4 5))

It is also possible to wrap C functions that return structs, by passing
a list to the first parameter of 'pointer->procedure', and then using
'parse-c-struct' to extract the fields of the returned struct.

Hope this helps!

    Mark



reply via email to

[Prev in Thread] Current Thread [Next in Thread]