Page 1 of 1

How can I change this defmacro so I can setf the return

Posted: Wed Jul 02, 2014 5:53 pm
by joeish80829
Here is the macro, a macro for cffi::mem-aref. I was trying to make it so I can setf it like you can with mem-aref, but can't figure out how to do it. Any help is appreciated.

Code: Select all

(defmacro ? (ptr type &optional (index 0))
  `(cond ((pointerp ,ptr)
	  (return-from ? (mem-aref ,ptr ,type ,index)))
	 ((not (pointerp ,ptr))
	  (return-from ? mem-aref (c-pointer ,ptr) ,type  ,index)))
          (t 0)))

Re: How can I change this defmacro so I can setf the return

Posted: Thu Jul 03, 2014 10:32 am
by Goheeca
It's a question, how (setf (mem-aref ...) ...) is implemented so probably you can't write:

Code: Select all

(defun resolve-pointer (ptr)
  (if (pointerp ptr) ptr (c-pointer ptr)))

(defmacro ? (ptr type &optional (index 0))
  `(mem-aref (resolve-pointer ,ptr) ,type ,index))
which result in:

Code: Select all

(setf (? *ptr* *type* *index*) ...) ; => (setf (mem-aref (resolve-pointer *ptr*) *type* *index*) ...)
You don't want to put a comma before the whole first argument of mem-aref, because it will determine the type of ptr in compile-time, but the way I presented it won't probably work, because the setf machinery doesn't evaluate its first argument, whence it doesn't evaluate resolve-pointer. In that case you must teach the setf what to do by telling via defsetf or define-setf-expander, which isn't so simple, but it's good to tackle.

Re: How can I change this defmacro so I can setf the return

Posted: Thu Jul 03, 2014 12:38 pm
by joeish80829
Can you show me how I would use desetf in this case, not sure I understood the documentation

Re: How can I change this defmacro so I can setf the return

Posted: Thu Jul 03, 2014 12:56 pm
by Goheeca
Ok, I've tested the code above with:

Code: Select all

(defun resolve-pointer (ptr) ptr)
and it works, no more labour is needed.

Re: How can I change this defmacro so I can setf the return

Posted: Thu Jul 03, 2014 6:31 pm
by joeish80829
Thank you very much, it didn't even occur to me to write an external function. Its blazing fast too! Thanks:)