gpt4 book ai didi

metaprogramming - Julia:构建符号表达式

转载 作者:行者123 更新时间:2023-12-04 06:53:55 24 4
gpt4 key购买 nike

我有一组重复的样板代码,如下所示:

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) 但我无法复制它。有没有办法在这种情况下生成所需的符号?

谢谢。

最佳答案

更新:原始答案有效(见下文),但正如@mlubin 指出的那样,QuoteNode 是一个内部实现函数。 Base.Meta 中的quot 函数比较好:

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

返回 :(:createObj1)。但我认为 Meta.quot 也没有记录在案。

原始答案:您正在寻找 QuoteNode:

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

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

关于metaprogramming - Julia:构建符号表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26412515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com