R代码加密

 

# =========================
# 打包 Rdata 文件
# =========================
# script.R 内容
my_function <- function(x) {
  return(x^2 + 2*x + 1)
}

# 加载 compiler 包
library(compiler)

# 运行 script.R 文件以定义函数
source("script.R")

# 编译函数
compiled_function <- cmpfun(my_function)

# 删除源代码属性 - 没啥用,view 还能看到
attr(compiled_function, "srcref") <- NULL
attr(compiled_function, "srcfile") <- NULL

# 删除可能的源代码属性 - 没啥用,view 还能看到
attributes(compiled_function) <- NULL

# 保存编译后的函数到 .RData 文件
# save(object1, object2, file = "my_data.RData")  # 保存指定对象
# save.image(file = "my_data.RData")  # 保存当前环境所有对象
save(compiled_function, file = "compiled_functions.RData")

# 加载 .RData 文件
# source("compiled_functions.RData")
# load("compiled_functions.RData")

# 命令行执行
# Rscript script.R input.json output.json


# =========================
# 将核心代码写到自定义环境里 ***************
# =========================
# 在你的包的 R 代码中
my_env <- new.env()

my_env$my_function <- function(x) {
  return(x^2 + 2*x + 1)
}

# 提供一个接口函数
my_function <- function(x) {
  my_env$my_function(x)
}


# =========================
# Rcpp:通过 Rcpp,可以将 R 函数用 C++ 实现,编译成动态链接库,用户无法直接查看源码。
# =========================
// 在 src 目录中创建一个 C++ 文件,例如 my_function.cpp
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double my_function(double x) {
  return x*x + 2*x + 1;
}

// 在 R 中调用
#' My function
#' @export
my_function <- function(x) {
  .Call('_mypackage_my_function', PACKAGE = 'mypackage', x)
}


# =========================
# 项目打包
# =========================
#

 R项目打包参考https://www.cnblogs.com/iupoint/p/18632470

 

posted on 2025-02-05 10:04  iUpoint  阅读(93)  评论(0)    收藏  举报

导航