Julia: Creating Symbolic Expressions

I have a repeating set of templates that looks like this:

type Object
    ptr::Ptr{Void}

    function Object()
        ptr = ccall( (:createObject, LIB_SMILE), Ptr{Void}, ())
        smart_p = new(ptr)
        finalizer(smart_p, obj -> ccall( (:freeObject, LIB_SMILE), Void, (Ptr{Void},), obj.ptr ))
        smart_p
    end
end

      

I would like to automatically generate a set of these types of definitions:

for str = ("Obj1","Obj2","Obj3")
    op_fname = symbol(str)
    op_create = ???
    op_free   = ???

    @eval begin
        type $op_fname
            ptr::Ptr{Void}

            function ($fname)()
                ptr = ccall( ($op_create, LIB_SMILE), Ptr{Void}, ())
                smart_p = new(ptr)
                finalizer(smart_p, obj -> ccall( ($op_free, LIB_SMILE), Void, (Ptr{Void},), obj.ptr ))
                smart_p
            end
        end
    end
end

      

I have not figured out how to generate the correct "character characters" for op_create and op_free. As in, I need to op_create = :(:createObj)

, but I cannot reproduce this. Is there a way to generate the required symbol in this context?

Thank.

+3


source to share


1 answer


Update: The original answer works (see below) but, as @mlubin points out, QuoteNode

is an internal implementation function. The function quot

is Base.Meta

better:

import Base.Meta.quot
str = "Obj1"
quot(symbol("create$str"))

      

returns :(:createObj1)

. But I don't think Meta.quot is also documented.



Original answer: You are looking for QuoteNode

:

str = "Obj1"
QuoteNode(symbol("create$str"))

      

returns :(:createObj1)

But it looks like a clear macro app!

+4


source







All Articles