C++ 如何在使用RInside时检查R命令是否成功执行

C++ 如何在使用RInside时检查R命令是否成功执行,c++,r,rcpp,rinside,C++,R,Rcpp,Rinside,我想编写一个程序,使用RInside执行R命令,并判断结果是否为字符串。我创建了一个RInside实例,并使用其方法解析R命令,然后将结果存储在一个SEXP变量中。我过去常常检查结果的类型是否是字符串,然后使用其。问题是,当我试图解析错误命令(如paste('hello)时,程序的行为变得有些不可预测。程序如下所示: #include <RInside.h> #include <stdio.h> int main(int argc, char* argv[]) {

我想编写一个程序,使用RInside执行R命令,并判断结果是否为字符串。我创建了一个RInside实例,并使用其方法解析R命令,然后将结果存储在一个SEXP变量中。我过去常常检查结果的类型是否是字符串,然后使用其。问题是,当我试图解析错误命令(如
paste('hello
)时,程序的行为变得有些不可预测。程序如下所示:

#include <RInside.h>
#include <stdio.h>

int main(int argc, char* argv[])
{

        RInside *R = new RInside();
        const char *expr = argv[1];

        SEXP res = NULL;
        try{
                res = R->parseEval(expr);
        } catch (std::exception &e) {
                res = NULL;
                printf("Exception thrown\n");
        }

        printf("res points to %p\n", res);
        if (res != NULL && TYPEOF(res) == STRSXP) {
                Rcpp::String res_str = res;
                printf("The result is a string: %s\n", res_str.get_cstring());
        } else {
                printf("The result is not a string");
        }
}
并使用与前面相同的命令行参数“粘贴('hello')运行它,我得到了输出

res指向(零)

结果不是字符串

所以我的问题是,它为什么会这样?当一个人用
RInside::parseval
解析一个错误命令时,是否会抛出一个异常,或者结果是一个空指针,或者至少会发生其中一种情况?上面的代码是否正确地完成了它的工作

任何帮助都是感激的

编辑0:

在花费一些时间阅读代码后,R似乎将命令
paste('hello
)视为“不完整”,这意味着如果我们稍后发送另一个命令来“完成”它,它将成功执行

#include <RInside.h>
#include <stdio.h>

void test_R(RInside *R, const char *expr, int is_ok)
{
        SEXP res = R->parseEval(expr);
        if (is_ok) {
                std::string res_str = Rcpp::String(res);
                printf("The result is %s\n", res_str.c_str());
        }
}

int main()
{

        RInside R;
        const char *head = "paste('hello";
        const char *tail = "')";

        test_R(&R, head, 0); // This will parse "paste('hello"
        test_R(&R, tail, 1); // This will parse the rest of the command
}
#包括
#包括
无效测试(冲洗液*R,常量字符*expr,整型正常)
{
SEXP res=R->parseval(expr);
如果(你还好吗){
std::string res_str=Rcpp::string(res);
printf(“结果是%s\n”,res_str.c_str());
}
}
int main()
{
冲洗液R;
const char*head=“粘贴('hello'”;
const char*tail=“”)”;
test_R(&R,head,0);//这将解析“粘贴('hello)”
test_R(&R,tail,1);//这将解析命令的其余部分
}
上面代码的结果是

结果是你好


是的,它就像R命令提示符。或者像一行一行地读取一个R文件。一个不完整的语句中断当前的解析,但不阻止后续解析。如果发生错误,我们抛出一个C++异常。或者您不例外地调用我们。所有这些都已经存在了十年,对大多数人来说都是正常工作。
#include <RInside.h>
#include <stdio.h>

void test_R(RInside *R, const char *expr, int is_ok)
{
        SEXP res = R->parseEval(expr);
        if (is_ok) {
                std::string res_str = Rcpp::String(res);
                printf("The result is %s\n", res_str.c_str());
        }
}

int main()
{

        RInside R;
        const char *head = "paste('hello";
        const char *tail = "')";

        test_R(&R, head, 0); // This will parse "paste('hello"
        test_R(&R, tail, 1); // This will parse the rest of the command
}