Any way to access function installed by makeActiveBinding?

 ̄綄美尐妖づ 提交于 2019-12-06 18:51:57

问题


The title basically says it all.

If I do this ...

makeActiveBinding("x", function() runif(2), .GlobalEnv)
x
# [1] 0.7332872 0.4707796
x
# [1] 0.5500310 0.5013099

... is there then any way for me to examine x to learn what function it is linked to (and if not, why not)?

(In this case, I'd like to be able to learn that x was defined to be function() runif(2).)


回答1:


With a bit of noodling around in envir.c, I can get this to work:

#include <Rcpp.h>
using namespace Rcpp ;

#define HASHSIZE(x)      LENGTH(x)
#define HASHVALUE(x)    TRUELENGTH(x)

// [[Rcpp::export]]
SEXP get_binding_fun( std::string name, Environment env){
    SEXP symbol = Rf_install( name.c_str() );
    SEXP tab = HASHTAB(env) ;
    SEXP c = PRINTNAME(symbol);

    // finding the hash code for the symbol
    int hashcode = HASHVALUE(c) % HASHSIZE(tab);

    // get the value there from the hash table
    SEXP res = CAR( VECTOR_ELT(tab, hashcode ) ) ;

    return res ;
}

Save this into a .cpp file, sourceCpp it and use it with this R code:

> makeActiveBinding("x", function() runif(2), .GlobalEnv)
> get_binding_fun("x", .GlobalEnv)
# function ()
# runif(2)


来源:https://stackoverflow.com/questions/16069566/any-way-to-access-function-installed-by-makeactivebinding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!