0Pricing
WebAssembly (WASM) for High Performance Apps · Урок

Вызов функций JavaScript из C/C++

Освойте обратное взаимодействие: вызывайте JavaScript из скомпилированного кода C/C++ WASM с помощью инструментов взаимодействия Emscripten.

«Вызов функций JavaScript из C/C++» — бесплатный урок WebAssembly (WASM) for High Performance Apps на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения WebAssembly (WASM) for High Performance Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс WebAssembly (WASM) for High Performance Apps содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Two-Way Interop

So far you have called C/C++ from JavaScript. But WASM code often needs to reach back into JS, to log, manipulate the DOM, or call browser APIs.

Emscripten provides several ways for your C/C++ code to call JavaScript.

Why Call JS at All?

WASM is sandboxed, it cannot touch the DOM, fetch, or timers directly. Anything outside pure computation must go through JavaScript.

  • Update the page
  • Read user input
  • Use Web APIs like localStorage

EM_JS: Inline JavaScript

The EM_JS macro lets you define a C function whose body is JavaScript. Call it like any C function.

#include <emscripten.h>

EM_JS(void, js_log, (int x), {
  console.log('Value from C: ' + x);
});

int main() { js_log(42); return 0; }

EM_ASM: Quick Inline Snippets

For one-off JS, EM_ASM runs a JavaScript snippet inline without declaring a separate function.

EM_ASM({
  document.title = 'Set from C++';
});

Passing Values to JS

EM_ASM_ variants let you pass arguments and receive return values.

int sum = EM_ASM_INT({
  return $0 + $1;
}, 10, 20);
// sum == 30

Passing Strings

Strings live in WASM memory. Use Emscripten helpers like UTF8ToString to read a C string pointer in JS.

EM_JS(void, show, (const char* msg), {
  console.log(UTF8ToString(msg));
});

JavaScript Library Files

For larger interop, put JS functions in a library file and link it with --js-library.

// mylib.js
mergeInto(LibraryManager.library, {
  beep: function() { console.log('beep'); }
});

Declaring Imported Functions in C

Functions from a JS library are declared extern in C so the compiler links them.

extern void beep();
int main() { beep(); return 0; }

Calling Exported C Functions Back

JS can hand a C function pointer back, useful for callbacks, via Module.cwrap or function pointers passed across the boundary.

const tick = Module.cwrap('tick', 'number', []);
setInterval(() => console.log(tick()), 1000);

Performance Note

Crossing the JS/WASM boundary has overhead. Keep hot loops inside WASM and call JS only at boundaries (I/O, DOM), not inside tight inner loops.

Best Practices Summary

For calling JS from C/C++:

  • Use EM_JS for named JS functions, EM_ASM for snippets
  • Convert pointers with UTF8ToString
  • Use a JS library file for substantial interop
  • Minimize boundary crossings in hot paths

Quick Check

Which Emscripten macro defines a C-callable function whose body is written in JavaScript?

Recap

You can now call JavaScript from your WASM code:

  • EM_JS and EM_ASM embed JS in C/C++
  • EM_ASM_INT passes args and returns values
  • JS library files handle larger interop
  • Keep boundary crossings out of hot loops

Two-way interop unlocks the full power of the browser from compiled code.

Часто задаваемые вопросы

Урок «Вызов функций JavaScript из C/C++» бесплатный?

Да — полный текст урока «Вызов функций JavaScript из C/C++» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс WebAssembly (WASM) for High Performance Apps, подпишись на CoddyKit PRO. Курс WebAssembly (WASM) for High Performance Apps содержит 4 уроков всего.

Чему я научусь в уроке «Вызов функций JavaScript из C/C++»?

Освойте обратное взаимодействие: вызывайте JavaScript из скомпилированного кода C/C++ WASM с помощью инструментов взаимодействия Emscripten. Ты практикуешь WebAssembly (WASM) for High Performance Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать WebAssembly (WASM) for High Performance Apps?

Предыдущий опыт не требуется. WebAssembly (WASM) for High Performance Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Вызов функций JavaScript из C/C++»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке WebAssembly (WASM) for High Performance Apps?

Да. Каждый урок WebAssembly (WASM) for High Performance Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Компиляция C/C++ в WASM с Emscripten
  2. Загрузка и запуск WASM в JavaScript
  3. Базовый обмен данными: примитивы
  4. Вызов функций JavaScript из C/C++
← Назад к WebAssembly (WASM) for High Performance Apps