通过地址/指针访问对象 [英] Access object by address / pointer
本文介绍了通过地址/指针访问对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过其内存地址或指针访问在当前R会话中创建的data.table对象吗?
Can I access data.table object created in current R session by its memory address or pointer?
library(data.table)
DT <- data.table(a = 1:10, b = letters[1:10])
address(DT)
# [1] "0x6bf9b90"
attr(DT,".internal.selfref",TRUE)
# <pointer: 0x2655cc8>
推荐答案
这有点愚蠢(与可以在C ++中强制转换指针相比),但是您可以:
This is somewhat of a silly way of doing it (as compared to how you can cast pointers in e.g. C++), but you could do:
# recursively iterate over environments
find.by.address = function(addr, env = .GlobalEnv) {
idx = which(sapply(ls(env), function(x) address(get(x, env = env))) == addr)
if (length(idx) != 0)
return (get(ls(env)[idx], env = env))
# didn't find it, let's iterate over the other environments
idx = which(sapply(ls(env), function(x) is.environment(get(x, env = env))))
for (i in idx) {
res = find.by.address(addr, get(ls(env)[i], env = env))
if (res != "couldn't find it") return (res)
}
return ("couldn't find it")
}
DT = data.table(a = 1)
e = new.env()
e$DT = data.table(b = 2)
e$f = new.env()
e$f$DT = data.table(c = 2)
find.by.address(address(DT))
# a
#1: 1
find.by.address(address(e$DT))
# b
#1: 2
find.by.address(address(e$f$DT))
# c
#1: 2
这篇关于通过地址/指针访问对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文