Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
EmscriptenでC/C++アプリをWASM化してブラウザで動かしてみた
Search
AGAWA Koji
June 12, 2024
Programming
670
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
EmscriptenでC/C++アプリをWASM化してブラウザで動かしてみた
AGAWA Koji
June 12, 2024
More Decks by AGAWA Koji
See All by AGAWA Koji
Software Architecture in an AI-Driven World
atty303
80
47k
PipeCDプラグインへの期待 / Anticipating PipeCD Plugins
atty303
0
130
良いソフトウェアとコードレビュー / Good software and code review
atty303
38
18k
Scala + Caliban で作るGraphQL バックエンド / Making GraphQL Backend with Scala + Caliban
atty303
0
600
Scala.jsとAndroidでドメイン層を共有しよう / Scala.js and Android
atty303
0
820
もう一つのビルドツール mill で作る Docker イメージ / Build docker image with mill the yet another build tool
atty303
2
2.6k
Case of Ad Delivery System is Implemented by Scala and DDD
atty303
4
3.7k
ログのメトリックを取ってみる話
atty303
0
1k
ADC2016: Axion meets HashiCorp
atty303
0
840
Other Decks in Programming
See All in Programming
ECSアプリログをFireLensでコスト削減しようとしたけど諦めた話 in Fargate×Node.js
akihisaikeda
2
4.2k
AI時代のUIはどこへ行く?その2!
yusukebe
22
7.7k
OS アップデート対応の取り組み方がもっと共有されてほしい
andpad
0
110
「AIで開発し、AIを届ける」をEvalでつなぐ 〜AIネイティブに始めるプロダクト開発の実践〜 / Connecting "Develop with AI, deliver AI" with Eval
rkaga
4
5.6k
dRuby over BLE
makicamel
2
400
ローカルLLMでどこまでコードが書けるか -拡張版 / How much code can be written on a local LLM Extended
kishida
12
4.6k
Spring Security 実践 ─ GraphQL APIで実務に役立つ 認証・認可 を学ぶ
wagyu
0
270
ローカルLLMでどこまでコードが書けるか -縮小版 / How much code can be written on a local LLM Shortened
kishida
2
170
The NotImplementedError Problem in Ruby
koic
1
1.1k
ローカルLLMを使ってB2Bサービスを作っていての学び
yaotti
0
230
「正の参照」と 「負の導出」で組む ハーネスエンジニアリング
cottpan
1
100
Javaの型とAI時代に型が大事な理由 / java types and type in AI era
kishida
2
160
Featured
See All Featured
Reality Check: Gamification 10 Years Later
codingconduct
0
2.2k
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
2
280
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
880
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
32
3.6k
Building an army of robots
kneath
306
46k
The Curious Case for Waylosing
cassininazir
1
420
Designing for humans not robots
tammielis
254
26k
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
0
180
AI Search: Where Are We & What Can We Do About It?
aleyda
0
7.7k
<Decoding/> the Language of Devs - We Love SEO 2024
nikkihalliwell
1
270
Game over? The fight for quality and originality in the time of robots
wayneb77
1
210
Max Prin - Stacking Signals: How International SEO Comes Together (And Falls Apart)
techseoconnect
PRO
0
200
Transcript
Emscriptenで C/C++アプリを WASM化してブラウザで動 かしてみた Koji AGAWA @atty303
Koji AGAWA @atty303 ソフトウェアエンジニア AI事業本部 ミライネージ 普段は Scala書いてます (10年弱 )
趣味で Rust書いてます (半年 ) #times_atty303
今回のターゲットアプリケーション
デスクトップ版
Web版
7日で 7000Visitsぐらい
PoBのアーキテクチャ
100% Lua ! Luaは、軽量で柔軟なスクリプト言語であり、組み込み用途やゲーム開発に広く使用され ている
Host Adapter 例えば描画に関係する関数はこれだけ GetScreenSize SetDrawLayer SetViewport SetDrawColor DrawImage DrawImageQuad DrawString
DrawStringWidth DrawStringCursorIndex
Luaをなんとかブラウザで動かせれば PoBのブラウザ版が作れそう Luaのオリジナル実装は C言語 他の言語( JSや Rust)での実装もあったが互換性に不安あり オリジナル実装をブラウザで動かしたい!
Compile your existing projects written in C or C++ —
or any language that uses LLVM — to browsers.
Emscriptenとは? LLVMをベースにしたコンパイラツールチェイン C/C++コードを WASMに変換する WASM黎明期からあるツールだがまだ開発が続いている Unityの WebGLエキスポートなどでも使われている
WebAssembly(WASM)とは? 主要なブラウザでサポートされる新しめの言語?ランタイム? 高速( GCがない!) JSと相互運用が可能
Emscriptenの使い方のイメージ 普通の CMakeでのビルド cd build cmake .. ninja Emscriptenによる CMakeでのビルド
cd build emcmake cmake .. ninja
Cと JSの相互作用
EM_ASM_JS / C → JS static int DrawStringWidth(lua_State *L) {
int n = lua_gettop(L); assert(n >= 3); assert(lua_isnumber(L, 1)); assert(lua_isstring(L, 2)); assert(lua_isstring(L, 3)); int height = lua_tointeger(L, 1); int font = luaL_checkoption(L, 2, "FIXED", fontMap); const char *text = lua_tostring(L, 3); int width = EM_ASM_INT({ return Module.getStringWidth($0, $1, UTF8ToString($2)); }, height, font, text); lua_pushinteger(L, width); return 1; } EM_ASM_JSマクロでインラインで JSが書ける
Asyncify EM_ASYNC_JS(int, paste, (), { var text = await Module.paste();
var lengthBytes = lengthBytesUTF8(text) + 1; var stringOnWasmHeap = Module._malloc(lengthBytes); stringToUTF8(text, stringOnWasmHeap, lengthBytes); return stringOnWasmHeap; }); static int Paste(lua_State *L) { const char *text = (const char *)paste(); lua_pushlstring(L, text, strlen(text)); free((void *)text); return 1; } Cから同期的に JSの Promiseを解決できる
cwrap / JS → C const onFrame = module.cwrap("on_frame", "number",
[], { async: true }); onFrame(); EMSCRIPTEN_KEEPALIVE int on_frame() { lua_State *L = GL; draw_begin(); void *buffer; size_t size; draw_get_buffer(&buffer, &size); EM_ASM({ Module.drawCommit($0, $1); }, buffer, size); draw_end(); return 0; }
WASMヒープ const wasmMemory = new WebAssembly.Memory(); const HEAPU8 = new
Uint8Array(wasmMemory.buffer); WASMのヒープは JSから見ると単なる ArrayBuffer Emscriptenでは HEAPU8などの TypedArrayが公開されている JSで mallocして Cで freeなどもできる
C/C++ ←→ JS のやりとりとメモリ表現がわかればあと はなんとかなった
高速化のために C/C++( WASM)から細かく JSの関数を呼ぶとそれなりに遅い なるべくそれぞれのランタイムに閉じる時間を長くする 描画関数は Cの世界でバッファに貯めて、フレーム終了時にまとめて JSへ転送
苦労するところ メモリ管理を間違えると例外が出る Cのメモリ破壊と同じく例外から原因が分からない デバッグビルド+サニタイザでパフォーマンスを犠牲にある程度デバッグできる
雑感 Emscripten+ WASMはかなり実用的 既存の C/C++コードの実行プラットフォームを広げたいときの選択肢としてアリ 新規で作る時は Rustなど WASMをネイティブサポートしている言語を使うほうが良いと 思う どちらにせよ昨今の
GCあり言語ほど楽ではないので覚悟は必要 WasmGCが実用レベルになってきているようなので GCあり言語から利用するのが一番 楽そう