返回从 C 到 R 的动态向量
我正在用 C 编写一些代码,以便从 R 动态调用。
该代码生成一条随机 泊松 过程的路径,直到所需的时间 T。 因此,每次调用我的 C 函数时,返回向量的长度都会有所不同,具体取决于生成的随机数。
我必须创建什么 R 数据结构? LISTSXP?另一个?
如何创建它以及如何附加它?特别是我如何将其返回给 R?
感谢您的帮助。
I am writing some code in C to be called dynamically from R.
This code generates a path of a random Poisson process up to a desired time T.
So at every call to my C function, the length of the returned vector will be different depending on the random numbers generated.
What R data structure will I have to create? a LISTSXP? another one?
How can I create it, and how can I append to it? And especially how can I return it back to R?
Thanks for help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这实际上取决于您想要使用什么作为临时结构,因为最终您无论如何都必须为结果分配一个向量。因此,无论您将使用什么,都不会返回什么。有几种可能性:
Calloc
+Realloc
+Free
,它允许您根据需要扩展临时内存。一旦获得完整的集合,就可以分配结果向量并返回它。SETLENGTH
。不过,这存在问题,因为结果将保持过度分配,直到稍后重复。它们各自都有缺点和优点,因此实际上取决于您的应用程序来选择最适合您的一种。
编辑:添加了使用配对列表方法的示例。我仍然推荐 Realloc 方法,因为它更容易,但尽管如此:
It's really up to you what you want to use as temporary structure, because in the end you'll have to allocate a vector for result anyway. So whatever you'll be using is not what you'll return. There are several possibilities:
Calloc
+Realloc
+Free
which allows you to expand the temporary memory as needed. Once you have the full set, you allocate the result vector and return it.SETLENGTH
before you return it. There are issues with this, though, because the result will remain over-allocated until duplicated later on.Each of them has drawbacks and benefits, so it really depends on your application to pick the one best suited for you.
Edit: added an example of using the pairlists approach. I would still recommend the
Realloc
approach since it's much easier, but nonetheless:如果您愿意从 C 切换到 C++,您可以免费获得附加的 Rcpp 层。下面是(仍然相当不完整)RcppExample 包页面中的一个示例:
如您所见,没有显式内存分配、释放、
PROTECT/UNPROTECT
等,并且您将获得第一类 R 列表对象。还有更多示例,包括 其他问题,例如就像这个。
编辑:你并没有真正说出你的路径会做什么,但作为一个简单的说明,这里是使用 Rcpp 添加
cumsum()
和的 C++ 代码rpois()
其行为就像在 R 中一样:作为证明,回到 R 中,如果我们设置种子,我们可以生成完全相同的数字:
If you're open to switching from C to C++, you get added layer of Rcpp for free. Here is an example from the page of the (still rather incomple) RcppExample package:
As you see, no explicit memory allocation, freeing,
PROTECT/UNPROTECT
etc, and you get a first class R list object back.There are lots more examples, included in other SO questions such as this one.
Edit: And you didn't really say what you paths would do, but as a simple illustration, here is C++ code using the Rcpp additions
cumsum()
andrpois()
which behave just like they do in R:And as a proof, back in R, if we set the seed, we can generate exactly the same numbers: