0Pricing
WebAssembly (WASM) for High Performance Apps · 课时

基本数据交换:原始类型

了解如何在 JavaScript 代码与 WASM 代码之间传递整数和浮点数等简单数据类型

基本数据交换:原始类型 是 CoddyKit 上的免费 WebAssembly (WASM) for High Performance Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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, and double are 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 Number type and C/C++'s primitive types.
  • Be mindful of potential precision differences when converting between 64-bit (JS Number, C double) and 32-bit (C float, C int) types.

This fundamental understanding paves the way for exchanging more complex data structures later on!

常见问题解答

「基本数据交换:原始类型」课时是免费的吗?

是的 — 「基本数据交换:原始类型」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebAssembly (WASM) for High Performance Apps 课程的其余内容,请升级到 CoddyKit PRO。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。

「基本数据交换:原始类型」这节课中我会学到什么?

了解如何在 JavaScript 代码与 WASM 代码之间传递整数和浮点数等简单数据类型 你通过在浏览器中直接运行的动手代码来练习 WebAssembly (WASM) for High Performance Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebAssembly (WASM) for High Performance Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebAssembly (WASM) for High Performance Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「基本数据交换:原始类型」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebAssembly (WASM) for High Performance Apps 课中编写并运行代码吗?

能。每节 WebAssembly (WASM) for High Performance Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 Emscripten 将 C/C++ 编译为 WASM
  2. 在 JavaScript 中加载并运行 WASM
  3. 基本数据交换:原始类型
  4. 从 C/C++ 调用 JavaScript 函数
← 返回 WebAssembly (WASM) for High Performance Apps