Reputation: 3231
I've been playing around with the fantastic cffi recently but I am having issues working out if something should be possible using the build in mechanisms.
I want to create a foreign array of vectors and have the foreign type translations set up such that this is possible.
> (defparameter a (foreign-alloc 'vec3 :count 10))
A
> (setf (mem-aref a 'vec3 4) (convert-to-foreign #(1.0 2.0 3.0) 'vec3))
#(1.0 2.0 3.0)
> (convert-from-foreign (mem-aref b 'vec3 4) 'vec3)
#(1.0 2.0 3.0
So far I have the following which allows the creating and getting of the foreign vec3 but not the retrieval.
(defcstruct %vec3
(components :float :count 3))
(define-foreign-type vec3-type ()
()
(:actual-type %vec3)
(:simple-parser vec3))
(defmethod translate-from-foreign (value (type vec3-type))
(make-array
3
:element-type 'single-float
:initial-contents (list (mem-aref value :float 0)
(mem-aref value :float 1)
(mem-aref value :float 2))))
The issue is that, while I can easily set up a function to act as a setter for the vec3, I would love there to be some in built way of doing this that I'm just not seeing. I have read the cffi manual and have seen the translate-to-foreign method and also the expand-to-foreign-dyn, but I haven’t found a way to use the to essentially expand to something like the following:
(let ((tmp (mem-aref a '%vec3 4)))
(setf (mem-aref tmp :float 0) (aref lisp-value 0))
(setf (mem-aref tmp :float 1) (aref lisp-value 1))
(setf (mem-aref tmp :float 2) (aref lisp-value 2)))
So that no extra memory is allocated and the values get set directly.
Well that's my little daydream, does anyone know if it can be made to work?
Upvotes: 4
Views: 673
Reputation: 3231
Had a read of the CFFI source code and it seems that this is not supported through the built in mechanisms. There is code there for handling array-types but it is not exposed or exported so is clearly not for use. There is also a proposed block memory interface but this has not been written yet.
So no dice this time, but CFFI is fantastic so I'll just make it in a different way.
p.s. There is also WAAF-CFFI that is worth looking into but I don't have specifics on this yet
Upvotes: 1