2014-10-16 85 views
3

我有一个重复的一组样板代码,看起来像这样:朱莉娅:建筑符号表达式

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 

我想自动生成一组这些类型定义的:

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 

我还没有想出如何为op_create和op_free生成正确的“符号符号”。如在,我需要op_create = :(:createObj),但我不能复制这个。有没有办法在这种情况下生成所需的符号?

谢谢。

回答

4

更新:原始答案有效(见下文),但是@mlubin指出,QuoteNode是一个内部实现函数。在Base.Metaquot功能更好:

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

回报:(:createObj1)。但我不认为Meta.quot也有记录。

原来的答复: 您正在寻找QuoteNode

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

回报:(:createObj1)但是,这似乎是一个宏观明确的应用程序!

+0

不错!有趣的是'QuoteNode'在Julia文档中不存在 – Mageek 2014-10-16 21:31:50

+0

我碰到它正在玩表达式:'typeof(:(a + b +:c).args [4])'给出'QuoteNode'。这与我所掌握的信息一样多。 – Gray 2014-10-16 21:34:15

+0

更好的方法是使用''Meta.quot''来替代''QuoteNode'',这是一个Julia内部。 – mlubin 2014-10-17 19:40:21