MCP HubMCP Hub
스킬 목록으로 돌아가기

add-rcpp-integration

pjt222
업데이트됨 Yesterday
2 조회
17
2
17
GitHub에서 보기
메타testing

정보

이 스킬은 R 패키지에 Rcpp 또는 RcppArmadillo를 통합하여 성능이 중요한 R 함수를 고성능 C++ 코드로 대체합니다. 설정 및 C++ 함수 작성부터 RcppExports 생성, 테스트, 디버깅에 이르는 전체 워크플로우를 다룹니다. 프로파일링으로 R에서 병목 현상을 확인했을 때, 기존 C/C++ 라이브러리와 인터페이스해야 할 때, 또는 루프 및 선형 대수와 같이 컴파일의 이점을 얻는 알고리즘을 구현할 때 사용하세요.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/add-rcpp-integration

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Add Rcpp Integration

Integrate C++ into R pkg via Rcpp → perf-critical ops.

Use When

  • R fn too slow, profile confirms bottleneck
  • Interface existing C/C++ libs
  • Algos benefit compiled (loops, recursion)
  • RcppArmadillo → linear algebra

In

  • Required: Existing R pkg
  • Required: R fn to replace/augment w/ C++
  • Optional: External C++ lib
  • Optional: RcppArmadillo? (default: plain Rcpp)

Do

Step 1: Rcpp Infra Setup

usethis::use_rcpp()

Does:

  • Creates src/ dir
  • Adds Rcpp → LinkingTo + Imports in DESCRIPTION
  • Creates R/packagename-package.R w/ @useDynLib + @importFrom Rcpp sourceCpp
  • Updates .gitignore for compiled

RcppArmadillo:

usethis::use_rcpp_armadillo()

src/ created, DESCRIPTION updated Rcpp LinkingTo + Imports, R/packagename-package.R has @useDynLib.

If err: usethis::use_rcpp() fails → manually create src/, add LinkingTo: Rcpp + Imports: Rcpp, add #' @useDynLib packagename, .registration = TRUE + #' @importFrom Rcpp sourceCpp to pkg doc file.

Step 2: Write C++ Fn

Create src/my_function.cpp:

#include <Rcpp.h>
using namespace Rcpp;

//' Compute cumulative sum efficiently
//'
//' @param x A numeric vector
//' @return A numeric vector of cumulative sums
//' @export
// [[Rcpp::export]]
NumericVector cumsum_cpp(NumericVector x) {
  int n = x.size();
  NumericVector out(n);
  out[0] = x[0];
  for (int i = 1; i < n; i++) {
    out[i] = out[i - 1] + x[i];
  }
  return out;
}

RcppArmadillo:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

//' Matrix multiplication using Armadillo
//'
//' @param A A numeric matrix
//' @param B A numeric matrix
//' @return The matrix product A * B
//' @export
// [[Rcpp::export]]
arma::mat mat_mult(const arma::mat& A, const arma::mat& B) {
  return A * B;
}

C++ src at src/my_function.cpp w/ valid // [[Rcpp::export]] + roxygen //' docs.

If err: Verify #include <Rcpp.h> (or <RcppArmadillo.h>), export annotation own line directly above signature, return types map valid Rcpp.

Step 3: Generate RcppExports

Rcpp::compileAttributes()
devtools::document()

R/RcppExports.R + src/RcppExports.cpp auto-generated.

If err: Check C++ syntax. Ensure // [[Rcpp::export]] above each exported fn.

Step 4: Verify Compilation

devtools::load_all()

Pkg compiles + loads no err.

If err: Check compiler out. Common:

  • Missing system headers → install dev libs
  • Syntax err → compiler msgs point to line
  • Missing Rcpp::depends for RcppArmadillo

Step 5: Tests for Compiled

test_that("cumsum_cpp matches base R", {
  x <- c(1, 2, 3, 4, 5)
  expect_equal(cumsum_cpp(x), cumsum(x))
})

test_that("cumsum_cpp handles edge cases", {
  expect_equal(cumsum_cpp(numeric(0)), numeric(0))
  expect_equal(cumsum_cpp(c(NA_real_, 1)), c(NA_real_, NA_real_))
})

Tests pass → C++ identical to R + edge cases (empty, NA) correct.

If err: NA fail → add explicit NA checks via NumericVector::is_na(). Empty fail → guard clause zero-length at top.

Step 6: Cleanup Script

Create src/Makevars:

PKG_CXXFLAGS = -O2

Create cleanup in pkg root (CRAN):

#!/bin/sh
rm -f src/*.o src/*.so src/*.dll

Make executable: chmod +x cleanup

src/Makevars sets compiler flags, cleanup removes objects. Both at pkg root.

If err: Verify cleanup has exec perms (chmod +x cleanup), Makevars tabs (not spaces) for Makefile rules.

Step 7: Update .Rbuildignore

Handle compiled artifacts:

^src/.*\.o$
^src/.*\.so$
^src/.*\.dll$

.Rbuildignore patterns prevent compiled objects in tarball, preserve src + Makevars.

If err: devtools::check() → NOTEs about unexpected files in src/. Adjust patterns → exclude only .o, .so, .dll.

Check

  • devtools::load_all() compiles no warn
  • Compiled fn produces correct results
  • Tests pass edge cases (NA, empty, large)
  • R CMD check passes no compile warn
  • RcppExports generated + committed
  • Perf improvement via benchmarks

Traps

  • Forget compileAttributes(): Must regen RcppExports after C++ changes
  • Int overflow: double not int for large numerics
  • Memory mgmt: Rcpp auto-handles for Rcpp types; no manual delete
  • NA handling: C++ doesn't know R's NA. Check Rcpp::NumericVector::is_na()
  • Platform portability: Avoid platform-specific C++. Test Win, macOS, Linux.
  • Missing @useDynLib: Pkg doc must @useDynLib packagename, .registration = TRUE

  • create-r-package — pkg setup before Rcpp
  • write-testthat-tests — testing compiled fns
  • setup-github-actions-ci — CI needs C++ toolchain
  • submit-to-cran — compiled pkgs need extra CRAN checks

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman-ultra/skills/add-rcpp-integration
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

content-collections

메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기

polymarket

메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기

creating-opencode-plugins

메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기

sglang

메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기