c - 如何使用 SWIG 创建带有可选参数的 TCL 函数?

标签 c arguments tcl swig

我有一个简单的 c/c++ 应用程序,它有一个可选的 TCL 解释器和使用 SWIG 生成的函数包装器。对于几个函数,所有参数都是可选的。这通常是如何处理的?我想支持这样的 TCL 命令,其中任何参数都是可选的,但 C 函数采用固定参数:

 //TCL command
 get_list [options] filename
   -opt1
   -opt2
   -opt3 arg1 
   -opt4 arg2
   filename

//C function
static signed get_list(bool         opt1,
                       bool         opt2,
                       char       * arg1,
                       objectType * arg2,
                       char       * fileName)

目前我有这样的东西:

static pList * get_list(char    * arg1=NULL,
                        char    * arg2=NULL, 
                        char    * arg3=NULL,  
                        tObject * arg4=NULL)

这有很多问题,例如强制对象指针始终是最后一个参数。 SWIG 文档详细讨论了使用“...”的可变参数的 C 函数,但我认为这不是我需要的。我希望修复 C 函数参数。

最佳答案

最简单的方法是在外面包裹一个 Tcl 过程,如下所示:

rename get_list original.get_list
proc get_list args {
    if {[llength $args] == 0 || [llength $args] % 2 == 0} {
        error "wrong # args: ...";   # Do a proper error message here!
    }
    # Handle the required argument
    set filename [lindex $args end]
    # Initialize the defaults
    array set opts {
        -opt1 false
        -opt2 false
        -opt3 ""
        -opt4 ""
    }
    # Merge in the supplied options
    foreach {opt val} [lrange $args 0 end-1] {
        if {![info exist opts($opt)]} {
            error "unrecognized option \"$opt\""
        }
        set opts($opt) $value
    }
    # Hand off to C level...
    original.get_list $opts(-opt1) $opts(-opt2) $opts(-opt3) $opts(-opt4) $filename
}

如果你有 Tcl 8.6,最后的切换最好用 tailcall 完成,这样重写代码就被从 Tcl 堆栈中删除了。但这并不重要,因为 SWIGged 代码很少解析 Tcl 命令和变量的名称。

关于c - 如何使用 SWIG 创建带有可选参数的 TCL 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7223437/

相关文章:

c - 使用 AVX 指令和 -O3 编译选项得到错误的结果

c - 为什么我得到 NULL is undefined 错误?

shell - (Tcl?)用于运行带有 testbench 作为 shell 参数的 modelsim 的脚本

sorting - tcl 有部分排序命令吗?

list - TCL从列表中删除元素

C 如何计算long变量中最长的连续0序列的长度?

command-line - 将命令行参数传递给LaTeX文档

Drupal 6 View 。如何使 View 标题成为节点 id 参数的节点标题?

python - 在 __init__ 的 scrapy 管道中使用参数

c++ - 访问与某个位置直接相邻的多维数组中的所有位置?