Liam Healy ([info]lhealy) wrote,
@ 2009-04-28 21:23:00
Previous Entry  Add to memories!  Tell a Friend  Next Entry
Entry tags:lisp

Foreign structures by value
I have written Foreign Structures By Value which will allow calling foreign functions that either take or return structures by value instead of by reference (i.e., with a pointer). It requires CFFI and libffi, and should work in any environment where those are both supported.

For example, the complex type is defined in the GNU Scientific Library (GSL) as

typedef struct
  {
    double dat[2];
  }
gsl_complex;

The function gsl_complex_conjugate takes and returns a structure of this type by value,

gsl_complex gsl_complex_conjugate (gsl_complex z);

If we define

(fsbv:defcstruct (complex :constructor complex :deconstructor (realpart imagpart))
  (dat :double :count 2))
(defun complex-conjugate (complex-number)
  (fsbv:with-foreign-objects ((gslin 'complex complex-number))
    (object
     (fsbv:foreign-funcall "gsl_complex_conjugate" complex gslin complex)
     'complex)))

then we can call this function from Lisp:
(complex-conjugate #c(3.0d0 4.0d0))
#C(3.0 -4.0)

This is making its way into GSLL but in the meantime should be usable for other projects.




(4 comments) - (Post a new comment)


[info]dmitry_vk
2009-04-29 04:58 am UTC (link)
Is it possible to implement f-s-b-v without using libffi?

(Reply to this) (Thread)


(Anonymous)
2009-04-29 10:25 am UTC (link)
No, it's not possible to do that portably. You would need to muck with assembly in order to implement the calling convention of the various platforms.

(Reply to this) (Parent)(Thread)

Need for libffi?
[info]lhealy
2009-04-29 12:52 pm UTC (link)
...which is exactly what libffi does for you. In a post in January, I showed how to hack it for ia32/amd64, but that is not portable or very convenient for anything other than the simplest structures. A commentor mentioned libffcall there, but I found libffi independently. These two libraries appear to do similar things, but it seems that libffi is more widely ported/maintained, and I found it better documented for the purposes of passing structures.

(Reply to this) (Parent)

Structures by value
[info]skypher.myopenid.com
2009-04-29 06:38 pm UTC (link)
That's cool functionality, thanks!

(Reply to this)


(4 comments) - (Post a new comment)

Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…