GNU 诡计:使用 scm_c_define_gsubr 注册的函数:我如何处理可选参数?

GNU guile: function registered with scm_c_define_gsubr: how can i handle an optional parameter?

我定义了一个狡猾的 C 函数:

static SCM myfun(SCM arg1,SCM opt_arg2)
  {
  return SCM_BOOL_T;
  }

已注册

scm_c_define_gsubr ("myfun", 1, 1, 0, myfun);

有一个 可选 参数。如何检测 opt_arg2 是否已被使用?

(myfun 1)

(myfun 1 2)

问题已在 guile-user 邮件列表中得到回答:http://lists.gnu.org/archive/html/guile-user/2017-12/msg00045.html

引用:Alex Vong

来自 Guile 手册``6.1 Guile 概述API'',

For some Scheme functions, some last arguments are optional; the corresponding C function must always be invoked with all optional arguments specified. To get the effect as if an argument has not been specified, pass ‘SCM_UNDEFINED’ as its value. You can not do this for an argument in the middle; when one argument is ‘SCM_UNDEFINED’ all the ones following it must be ‘SCM_UNDEFINED’ as well.

因此,我们可以检查 opt_arg2 是否具有值 SCM_UNDEFINED,以 决定我们是否收到可选参数。代码在 附件:

#include <libguile.h>

static SCM myfun(SCM arg1,SCM opt_arg2)
{
  if (scm_is_eq (opt_arg2, SCM_UNDEFINED))
    scm_display(scm_from_utf8_string("Optional argument NOT received!\n"),
                scm_current_output_port());
  else
    scm_display(scm_from_utf8_string("Optional argument received!\n"),
                scm_current_output_port());
  return SCM_BOOL_T;
}

void
init_myfun(void)
{
  scm_c_define_gsubr("myfun", 1, 1, 0, myfun);
}