参数如何传递到 cppFunction [英] How arguments are passed into a cppFunction

查看:37
本文介绍了参数如何传递到 cppFunction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用 Rcpp 时,我对如何将参数传递到 cppFunction 感到困惑.特别想知道有没有人能解释一下下面代码的结果.

I'm puzzled as to how arguments are passed into a cppFunction when we use Rcpp. In particular, I wonder if someone can explain the result of the following code.

library(Rcpp)
cppFunction("void test(double &x, NumericVector y) {
    x = 2016;
    y[0] = 2016;
}")
a = 1L
b = 1L
c = 1
d = 1
test(a,b)
test(c,d)
cat(a,b,c,d) #this prints "1 1 1 2016"

推荐答案

如前所述,Rcpp 围绕 R 的 SEXP 对象建立了方便的类.

As stated before in other areas, Rcpp establishes convenient classes around R's SEXP objects.

  • 对于第一个参数,double 类型没有默认的 SEXP 对象.这是因为在 R 中,没有标量这样的东西.因此,分配新内存使得 & 引用不兼容.因此,修改的变量范围仅限于函数,并且永远不会更新结果.因此,对于这两个测试用例,您将看到 1.
  • 对于第二种情况,对象类之间存在不匹配.由于在末尾附加了 L,这与 C++ 函数预期的 numeric 类型相冲突,因此提供的第一个调用对象的类型为 integer.当对象被实例化为 numeric 时,删除 L 后,问题就解决了.因此,不需要创建一个正确类型的中间内存位置来接收值.因此,第二种情况下的修改能够传播回 R.
  • For the first parameter, the double type does not have a default SEXP object. This is because within R, there is no such thing as a scalar. Thus, new memory is allocate making the & reference incompatible. Hence, the variable scope for the modification is limited to the function and there is never an update to the result. As a result, for both test cases, you will see 1.
  • For the second case, there is a mismatch between object classes. Within the first call object supplied is of type integer due to the L appended on the end, which conflicts with the C++ function expected type of numeric. The issue is resolved once the L is dropped as the object is instantiated as a numeric. Therefore, an intermediary memory location does not need to be created that is of the correct type to receive the value. Hence, the modification in the second case is able to propagate back to R.

例如

a = 1L
class(a)
# "integer"
a = 1
class(a)
# "numeric"

这篇关于参数如何传递到 cppFunction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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