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

Discussion of Common Lisp
Post Reply
joeish80829
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

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

Post by joeish80829 » Wed Jul 02, 2014 5:53 pm

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)))

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

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

Post by Goheeca » Thu Jul 03, 2014 10:32 am

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.
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

joeish80829
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

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

Post by joeish80829 » Thu Jul 03, 2014 12:38 pm

Can you show me how I would use desetf in this case, not sure I understood the documentation

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

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

Post by Goheeca » Thu Jul 03, 2014 12:56 pm

Ok, I've tested the code above with:

Code: Select all

(defun resolve-pointer (ptr) ptr)
and it works, no more labour is needed.
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

joeish80829
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

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

Post by joeish80829 » Thu Jul 03, 2014 6:31 pm

Thank you very much, it didn't even occur to me to write an external function. Its blazing fast too! Thanks:)

Post Reply