如何从 R 中检查 externalptr 是否为 NULL [英] How do I check if an externalptr is NULL from within R

查看:37
本文介绍了如何从 R 中检查 externalptr 是否为 NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SWIG 生成包装器代码以从 R 语言中访问 C 代码.包装器代码使用 R externalptr 类型来保存对 C 指针的引用.在某些情况下,这些指针在 C 端为 NULL,在 R 中显示时显示为 nil 值.在 R 端,在 externalptr 上调用 is.null()is.na() 都返回 FALSE>.例如:

I'm using SWIG to generate wrapper code to access C code from within the R language. The wrapper code uses the R externalptr type to hold references to C pointers. In some situations, those pointers are NULL on the C side, which show up in R as a nil value when displayed. On the R side, calling is.null() and is.na() on the externalptr both return FALSE. For example:

> val = librdf_query_results_get_binding_value(results, 2)
> val
An object of class "_p_librdf_node_s"
Slot "ref":
<pointer: (nil)>
> class(val@ref)
[1] "externalptr"
> is.null(val@ref)
[1] FALSE
> is.na(val@ref)
[1] FALSE

从上面的代码输出可以看出,ref 槽包含一个 externalptr,它是nil".如何从 R 中确定 C 中的此指针为 NULL?

As can be seen from the code output above, the ref slot contains an externalptr, which is "nil". How do I determine from within R that this pointer in C is NULL?

如果您想在上下文中查看代码,可以在 GitHub 中找到它:https://github.com/ropensci/redland-bindings/blob/master/R/redland/inst/tests/test.redland_base.R#L40

If you want to see the code in context, it is available in GitHub: https://github.com/ropensci/redland-bindings/blob/master/R/redland/inst/tests/test.redland_base.R#L40

推荐答案

为了完整起见,这里是我使用的解决方案.正如@DirkEddelbuettel 所建议的,它需要在 C 端有一个函数,在 R 端有一个函数.C函数是:

For completeness, here's the solution I used. It required a function on the C side, and one on the R side, as suggested by @DirkEddelbuettel. The C function is:

#include <Rinternals.h>

SEXP isnull(SEXP pointer) {
  return ScalarLogical(!R_ExternalPtrAddr(pointer));
}

R 中的包装函数是:

is.null.externalptr <- function(pointer) {
  stopifnot(is(pointer, "externalptr"))
  .Call("isnull", pointer)
}

R 中的使用示例:

> p <- new("externalptr")
> p
<pointer: (nil)>
> is.null.externalptr(p)
[1] TRUE

这篇关于如何从 R 中检查 externalptr 是否为 NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆