How do I check if an externalptr is NULL from within R

前端 未结 2 759
心在旅途
心在旅途 2021-01-21 12:05

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

相关标签:
2条回答
  • 2021-01-21 12:07

    The C solution above is most elegant, but a compiler might not always be available. A solution that does not require compiled code could be something like:

    identical(pointer, new("externalptr"))
    

    However this would not work if the object has custom attributes. If this is the case, you could do:

    isnull <- function(pointer){
      a <- attributes(pointer)
      attributes(pointer) <- NULL
      out <- identical(pointer, new("externalptr"))
      attributes(pointer) <- a
      return(out)
    }
    

    Again a bit more involved than the C solution, but will work in a simple script on any platform.

    0 讨论(0)
  • 2021-01-21 12:30

    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));
    }
    

    And the wrapper function in R is:

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

    For an example of use from within R:

    > p <- new("externalptr")
    > p
    <pointer: (nil)>
    > is.null.externalptr(p)
    [1] TRUE
    
    0 讨论(0)
提交回复
热议问题