我用 .c
语言构建自己的函数。然后,我构建了一个 R 函数来使用 .C
调用 .c
函数,例如
tmp <- .C("myfunction",
as.integer(N),
as.integer(n),
as.integer(w1),
as.integer(w2),
as.integer(w3),
PACKAGE = "mypackage")[[3]]
这被称为包装 R 函数。此外,我的函数基于或需要其他 .c
函数。据我所知,使用 Rcpp
使其更加灵活和简单,例如:
cppFunction('int add(int x, int y, int z) {
int sum = x + y + z;
return sum;
}')
我还知道 cppFunction
可以使用 C++
语言。但是,我发现 .c
函数和 .c++
之间没有太大区别。
我的问题是:我可以将 cppFunction
与需要包装 R 函数的 .c
函数一起使用吗?或者我需要先将我的 .c
函数转换为 .c++
函数?我的功能所基于的其他功能呢?这会像任何常规 R
函数一样吗?
我的意思是:假设我有两个 cppFunction
函数 myfunc1
和 myfunc2
,其中 myfunc2
基于 myfunc1
。然后假设我的第二个 cppFunction
如下:
cppFunction('int myfunc2(int x, int y, int z) {
int sum = x + y + z;
myfunc1 ## do some works here
return something;
}')
这样可以吗?还是我需要这样写:
cppFunction('int myfunc2(int x, int y, int z) {
int sum = x + y + z;
cppFunction('int myfunc2(int some arguments) {## do some works here}
return something;
}')
一般如何使用构建包含多个函数的cppFunction
?
有什么帮助吗?
最佳答案
这是一个使用外部 cpp 文件的示例。
这些函数可以在同一文件内交互,但就像其他人所说的那样,您必须使用 header 才能使用其他文件中的函数。
你必须在你想要在 R 中使用的任何函数之前使用 //[[Rcpp::export]]
。
(感谢@F.Privé 改进代码)
1) 文件 cpp:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double sumC(NumericVector x) {
int n = x.size();
double total = 0;
for(int i = 0; i < n; ++i) {
total += x[i];
}
return total;
}
// [[Rcpp::export]]
double meanC(NumericVector x) {
return sumC(x) / x.size();
}
文件 R:
Rcpp::sourceCpp("your path/mean.cpp")
x <- 1:10
meanC(x)
sumC(x)
2)使用 cppfunction 的替代方法。你必须使用包含参数
cppFunction('double meanC(NumericVector x) {
return sumC(x) / x.size();
}',includes='double sumC(NumericVector x) {
int n = x.size();
double total = 0;
for(int i = 0; i < n; ++i) {
total += x[i];
}
return total;
}')
无论如何,我建议您使用 sourceCpp,使用独立文件会产生更易于维护和更干净的代码
3)使用 sourceCPP 和多个 cpp 文件。你必须使用头文件,并为每个你想在其他 cpp 文件中使用的 file.cpp 做一个头文件。
sum.h文件(ifndef防止多重定义)
#include <Rcpp.h>
#ifndef SUM1
#define SUM1
double sumC(Rcpp::NumericVector x);
#endif
sum.cpp(和之前一样)
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double sumC(NumericVector x) {
int n = x.size();
double total = 0;
for(int i = 0; i < n; ++i) {
total += x[i];
}
return total;
}
均值.cpp文件 (你必须包含总和标题) #include "sum.h"
#include <Rcpp.h>
#include "sum.h"
using namespace Rcpp;
// [[Rcpp::export]]
double meanC(NumericVector x) {
return sumC(x) / x.size();
}
关于c++ - 我们可以将 Rcpp 与多个 C++ 函数一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45296381/