기본 데이터 교환: 원시 타입
JavaScript 코드와 WASM 코드 사이에서 정수와 부동 소수점 수 같은 단순한 데이터 타입을 전달하는 방법을 이해합니다.
기본 데이터 교환: 원시 타입은(는) CoddyKit의 무료 WebAssembly (WASM) for High Performance Apps 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebAssembly (WASM) for High Performance Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebAssembly (WASM) for High Performance Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Exchanging Basic Data Types
Welcome! In this lesson, we'll learn how to pass simple data types, known as primitives, between your JavaScript code and your WebAssembly (WASM) module compiled from C/C++.
Primitives include numbers like integers (int) and floating-point numbers (float, double). This is fundamental for enabling communication and interaction between your web application and high-performance WASM logic.
JS to WASM: Integer Input
Passing an integer from JavaScript to a C/C++ WASM function is quite direct. You define your C/C++ function with integer parameters, and Emscripten handles the necessary type mapping.
For example, a C function to add two integers would look like this:
int add_integers(int a, int b) {
// Function body
return a + b;
}Example: WASM Integer Function
Let's look at a complete C program that defines a function to add two integers and exposes it to JavaScript using EMSCRIPTEN_KEEPALIVE.
Try running this code and see how it compiles:
#include <stdio.h>
#include <emscripten/emscripten.h>
#ifdef __cplusplus
extern "C" {
#endif
EMSCRIPTEN_KEEPALIVE
int add_integers(int a, int b) {
printf("WASM: Adding %d and %d\n", a, b);
return a + b;
}
#ifdef __cplusplus
}
#endif
int main() {
printf("WASM module for integers loaded.\n");
return 0;
}Calling Integer Function from JS
After compiling the C code above, Emscripten generates a JavaScript glue code file (e.g., your_module.js) that provides access to your C functions.
You can then call the exported C function from your JavaScript code like this:
// Assuming 'Module' is the Emscripten-generated object
Module.onRuntimeInitialized = () => {
// The C function is prefixed with an underscore by default
const result = Module._add_integers(10, 25);
console.log(`Sum from WASM: ${result}`); // Output: Sum from WASM: 35
};WASM to JS: Integer Output
Returning an integer from a WASM function back to JavaScript is just as straightforward. C/C++ functions naturally return primitive types, and Emscripten ensures these return values are directly accessible in JavaScript.
Consider a C function that simply returns a fixed integer:
int get_magic_number() {
return 42;
}Example: WASM Returns Integer
Here's a C example that returns a specific integer. Notice the use of EMSCRIPTEN_KEEPALIVE to make it available to JavaScript.
Run this to see the simple C structure:
#include <stdio.h>
#include <emscripten/emscripten.h>
#ifdef __cplusplus
extern "C" {
#endif
EMSCRIPTEN_KEEPALIVE
int get_magic_number() {
printf("WASM: Returning magic number.\n");
return 42;
}
#ifdef __cplusplus
}
#endif
int main() {
printf("WASM module for returning integers loaded.\n");
return 0;
}Exchanging Floating-Point Numbers
Passing floating-point numbers (float and double) between JavaScript and WASM works very similarly to integers. You define your C/C++ functions with float or double parameters and return types.
JavaScript's Number type is generally a 64-bit float (double-precision), which Emscripten automatically converts when passing to C/C++ float (32-bit) or double (64-bit) types.
Example: WASM Float Operations
Let's create a C function that takes two floats and returns their product, and another for doubles. This demonstrates both input and output of floating-point numbers.
Run this code to see how floats are handled:
#include <stdio.h>
#include <emscripten/emscripten.h>
#ifdef __cplusplus
extern "C" {
#endif
EMSCRIPTEN_KEEPALIVE
float multiply_floats(float a, float b) {
printf("WASM: Multiplying floats %.2f * %.2f\n", a, b);
return a * b;
}
EMSCRIPTEN_KEEPALIVE
double divide_doubles(double x, double y) {
printf("WASM: Dividing doubles %.2f / %.2f\n", x, y);
if (y == 0.0) return 0.0; // Avoid division by zero
return x / y;
}
#ifdef __cplusplus
}
#endif
int main() {
printf("WASM module for floats/doubles loaded.\n");
return 0;
}Type Matching is Key
While Emscripten handles much of the type conversion automatically, it's good practice to be aware of the underlying types:
- JavaScript
Number: This is typically a 64-bit floating-point number. - C/C++
int: Often 32-bit integer. - C/C++
float: 32-bit floating-point number. - C/C++
double: 64-bit floating-point number.
When passing a JS Number to a C float, there might be a slight loss of precision, as the 64-bit JS number is truncated to a 32-bit float.
Quick Check: Data Flow
You've learned how simple data types are exchanged. Let's test your understanding.
Recap: Primitive Exchange
Great job! You've mastered the basics of primitive data exchange between JavaScript and WebAssembly modules compiled from C/C++.
- Simple data types like
int,float, anddoubleare straightforward to pass. - C/C++ functions can take them as parameters and return them as results.
- Emscripten acts as the bridge, automatically converting between JavaScript's
Numbertype and C/C++'s primitive types. - Be mindful of potential precision differences when converting between 64-bit (JS
Number, Cdouble) and 32-bit (Cfloat, Cint) types.
This fundamental understanding paves the way for exchanging more complex data structures later on!
자주 묻는 질문
“기본 데이터 교환: 원시 타입” 강의는 무료인가요?
네 — “기본 데이터 교환: 원시 타입” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebAssembly (WASM) for High Performance Apps 강의 전체를 잠금 해제할 수 있습니다. WebAssembly (WASM) for High Performance Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“기본 데이터 교환: 원시 타입”에서 뭘 배우나요?
JavaScript 코드와 WASM 코드 사이에서 정수와 부동 소수점 수 같은 단순한 데이터 타입을 전달하는 방법을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 WebAssembly (WASM) for High Performance Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebAssembly (WASM) for High Performance Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebAssembly (WASM) for High Performance Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“기본 데이터 교환: 원시 타입” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebAssembly (WASM) for High Performance Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebAssembly (WASM) for High Performance Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Emscripten으로 C/C++를 WASM으로 컴파일하기
- JavaScript에서 WASM 불러오고 실행하기
- 기본 데이터 교환: 원시 타입
- C/C++에서 JavaScript 함수 호출하기