RCpp 向量的 sizeof return 是什么
what does sizeof return for RCpp vectors
我想了解 c++ sizeof
在 RCpp 向量上运行时的作用。例如:
library(Rcpp)
cppFunction('int size_of(NumericVector a) {return(sizeof a);}')
size_of(1.0)
# [1] 16
此 returns 传递给它的任何数字或整数向量的值 16。
也是
cppFunction('int size_of(IntegerVector a) {return(sizeof a);}')
size_of(1)
# [1] 16
我认为 R 中的数字是 8 个字节,整数是 4 个字节。那么这里发生了什么?动机是在需要知道大小的 RCpp 向量上使用 memcpy
。
您必须了解 NumericVector
和 IntegerVector
的实现方式才能发现它们静态占用特定字节数的原因。
根据您对本上下文中 "numeric" 或 "integer" 大小的观察,值 16 可能占以下 any/all 的值:
- 指向 [dynamically-allocated?] 数据的指针
- 容器的当前逻辑大小(元素数)
- 任何其他元数据
理想情况下,不要使用memcpy
将一个对象的状态转移到另一个对象,除非您绝对确定它是一个只有成员的普通对象built-in 类型。如果我猜对了 NumericVector
的布局,在其上使用 memcpy
将违反其所有权语义,因此是不正确的。有other ways to copy R vectors.
Everything 我们从 R 传递到 C(++) 并且 return 是一个 SEXP
类型——一个 指针 到 S 表达式。
因此,如果我们概括您的函数并实际让 SEXP
进入,我们可以看到一些有趣的事情:
R> Rcpp::cppFunction('int size_of(SEXP a) {return(sizeof a);}')
R> size_of(1L) ## single integer -- still a pointer
[1] 8
R> size_of(1.0) ## single double -- still a pointer
[1] 8
R> size_of(seq(1:100)) ## a sequence ...
[1] 8
R> size_of(help) ## a function
[1] 8
R> size_of(globalenv) ## an environment
[1] 8
R>
简而言之,您陷入了 compile-time C++ 类型分析运算符 (sizeof
) 和 run-time 特性之间,即一切都变形为 SEXP
类型。对于实际向量,您可能需要 size()
或 length()
成员函数等。
我想了解 c++ sizeof
在 RCpp 向量上运行时的作用。例如:
library(Rcpp)
cppFunction('int size_of(NumericVector a) {return(sizeof a);}')
size_of(1.0)
# [1] 16
此 returns 传递给它的任何数字或整数向量的值 16。
也是
cppFunction('int size_of(IntegerVector a) {return(sizeof a);}')
size_of(1)
# [1] 16
我认为 R 中的数字是 8 个字节,整数是 4 个字节。那么这里发生了什么?动机是在需要知道大小的 RCpp 向量上使用 memcpy
。
您必须了解 NumericVector
和 IntegerVector
的实现方式才能发现它们静态占用特定字节数的原因。
根据您对本上下文中 "numeric" 或 "integer" 大小的观察,值 16 可能占以下 any/all 的值:
- 指向 [dynamically-allocated?] 数据的指针
- 容器的当前逻辑大小(元素数)
- 任何其他元数据
理想情况下,不要使用memcpy
将一个对象的状态转移到另一个对象,除非您绝对确定它是一个只有成员的普通对象built-in 类型。如果我猜对了 NumericVector
的布局,在其上使用 memcpy
将违反其所有权语义,因此是不正确的。有other ways to copy R vectors.
Everything 我们从 R 传递到 C(++) 并且 return 是一个 SEXP
类型——一个 指针 到 S 表达式。
因此,如果我们概括您的函数并实际让 SEXP
进入,我们可以看到一些有趣的事情:
R> Rcpp::cppFunction('int size_of(SEXP a) {return(sizeof a);}')
R> size_of(1L) ## single integer -- still a pointer
[1] 8
R> size_of(1.0) ## single double -- still a pointer
[1] 8
R> size_of(seq(1:100)) ## a sequence ...
[1] 8
R> size_of(help) ## a function
[1] 8
R> size_of(globalenv) ## an environment
[1] 8
R>
简而言之,您陷入了 compile-time C++ 类型分析运算符 (sizeof
) 和 run-time 特性之间,即一切都变形为 SEXP
类型。对于实际向量,您可能需要 size()
或 length()
成员函数等。