I want to embed a Java object (in this case a BufferedImage) in Clojure code that can be evald later.
Creating the code works fine:
(defn f [image]
`(.getRGB ~image 0 0))
=> #'user/f
(f some-buffered-image)
=> (.getRGB #<BufferedImage BufferedImage@5527f4f9: type = 2 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=ff000000 IntegerInterleavedRaster: width = 256 height = 256 #Bands = 4 xOff = 0 yOff = 0 dataOffset[0] 0> 0 0)
However you get an exception when trying to eval it:
(eval (f some-buffered-image))
=> CompilerException java.lang.RuntimeException: Can't embed object in code, maybe print-dup not defined: BufferedImage@612dcb8c: type = 2 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=ff000000 IntegerInterleavedRaster: width = 256 height = 256 #Bands = 4 xOff = 0 yOff = 0 dataOffset[0] 0, compiling:(NO_SOURCE_PATH:1)
Is there any way to make something like this work?
EDIT:
The reason I am trying to do this is that I want to be able to generate code that takes samples from an image. The image is passed to the function that does the code generation (equivalent to f above), but (for various reasons) can't be passed as a parameter to the compiled code later.
I need to generate quoted code because this is part of a much larger code generation library that will apply further transforms to the generated code, hence I can't just do something like:
(defn f [image]
(fn [] (.getRGB image 0 0)))
if) can use it just fine, i assume? if so, then it's probably because eval forces things to go through text (which makes sense for eval). if this is an issue for you, you may be using eval when it's not necessary - when a macro may be what you need.evaldoesn't really force things to go through text. Eval (via compile) generates JVM code that creates the objects. Going through text (via serialization) is the last resort used on unknown objects.(defn f [a] (fn [] (.getRGB a 0 0)))?