首页 > 解决方案 > 在 shinyapp.io 中编译 C++ 代码

问题描述

我有一个 C++ 代码(在文本文件中打印“hello world!”的 hello world 代码)。

#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
ofstream myfile;
myfile.open ("Hello_World.txt");
myfile << "Hello World! This is a test.\n";
myfile.close();
return 0;
}

我想看看是否可以在 shinyapp.io 上编译我的 C++ 代码,然后在服务器上执行编译后的文件并获取“Hello_World.txt”文件?如果没有,我应该如何在我的本地机器上编译我的代码,以便在我将编译后的代码传输到服务器后,它可以在 shinyapp.io 中执行?

我更关心这种方法(在本地机器上编译 Fortran 或 C++ 代码并在 shinyapp.io 上运行)。我的目标是在将来扩展更复杂代码的方法。

标签: c++rshinyshinyapps

解决方案


您可以毫无问题地编译 cpp 文件,请查看您的代码为 shinyapp.io 采用和部署:

应用程序.R:

library(Rcpp)
library(shiny)

Rcpp::sourceCpp("test_rcpp.cpp")


shiny::shinyApp(

  ui = fluidPage(
    titlePanel(hello()),
    sidebarLayout(
      sidebarPanel("content of Hello_world.txt"),
      mainPanel(readChar("Hello_World.txt", file.info("Hello_World.txt")$size))
    )
  ),
  server = function(input, output, session) {
  }
)

test_rcpp.cpp:

#include <Rcpp.h>
#include <iostream>
#include <fstream>
using namespace Rcpp;
using namespace std;

// This is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp 
// function (or via the Source button on the editor toolbar). Learn
// more about Rcpp at:
//
//   http://www.rcpp.org/
//   http://adv-r.had.co.nz/Rcpp.html
//   http://gallery.rcpp.org/
//

// [[Rcpp::export]]
CharacterVector hello() {
  ofstream myfile;
  myfile.open ("Hello_World.txt");
  myfile << "Hello World! This is a test.\n";
  myfile.close();
  return "Hello, World is saved";
;
}


// You can include R code blocks in C++ files processed with sourceCpp
// (useful for testing and development). The R code will be automatically 
// run after the compilation.
//

/*** R
*/

输出: 在此处输入图像描述


推荐阅读