0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windows11 の VSCode+Emscripten で wasm によるハローワールド (15)

Last updated at Posted at 2025-10-14

すべての記事

依存するファイルの解決

以前の記事 では Module.dynamicLibraries を利用していたため、依存するサイド・モジュールのダウンロード数を自動的に Module.monitorRunDependencies で監視できていた。

しかし、依存するファイルがデータ・ファイルの場合は自分で管理する必要があり、そのためのコードの記述が必要になる。
addRunDependencyremoveRunDependency はそのための関数になる。

以下では C++ のコードが必要とするデータ・ファイルのダウンロードを Module.monitorRunDependencies により監視している。

C:\wasm\project\12-monitor-dependencies\.vscode\launch.json

{
    "version": "0.2.0",
    "configurations": [

        {
            "type": "chrome",
            "request": "launch",
            "name": "localhost:8080",
            "url": "http://localhost:8080/",
        }
    ]
}

C:\wasm\project\12-monitor-dependencies\CMakePresets.json

{
  "version": 5,
  "cmakeMinimumRequired": {
    "major": 3,
    "minor": 20,
    "patch": 0
  },
  "configurePresets": [
    {
      "name": "wasm-config",
      "hidden": true,
      "generator": "Ninja Multi-Config",
      "binaryDir": "${sourceDir}/build",
      "cacheVariables": {
        "CMAKE_CXX_STANDARD": "17",
        "CMAKE_CXX_STANDARD_REQUIRED": "ON",
        "CMAKE_CXX_EXTENSIONS": "OFF",
        "CMAKE_TOOLCHAIN_FILE": "$env{EMSDK}/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake",
        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
        "CMAKE_CONFIGURATION_TYPES": "Debug;Release"
      }
    },
    {
      "name": "wasm-config-debug",
      "inherits": "wasm-config",
      "cacheVariables": {
      }
    },
    {
      "name": "wasm-config-release",
      "inherits": "wasm-config",
      "cacheVariables": {
      }
    }
  ],
  "buildPresets": [
    {
      "name": "wasm-build-debug",
      "configurePreset": "wasm-config-debug",
      "verbose": true,
      "configuration": "Debug"
    },
    {
      "name": "wasm-build-release",
      "configurePreset": "wasm-config-release",
      "verbose": true,
      "configuration": "Release"
    }
  ]
}

C:\wasm\project\12-monitor-dependencies\CMakeLists.txt
fetch で取得したファイルを仮想ファイルシステムに出力するために FS のエクスポートが必要になる

cmake_minimum_required(VERSION 3.20)
project(12_monitor_dependencies LANGUAGES CXX)

add_executable(12_monitor_dependencies main.cpp)
target_link_options(12_monitor_dependencies PRIVATE
    $<$<CONFIG:Debug>:-gsource-map -sASSERTIONS=1 -sSAFE_HEAP=1>
    "-sEXPORTED_RUNTIME_METHODS=addRunDependency,removeRunDependency,FS"
    "-sEXPORT_ES6"
)

C:\wasm\project\12-monitor-dependencies\index.html

  • preRun では、addRunDependency で依存関係のカウントを増やし、ファイルの保存後に removeRunDependency でカウントを減らす
  • C++ のコードは上記のカウントが 0 になるまで実行が待たされる
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8"/>
        <script type="module">
            import Module from './build/Debug/12_monitor_dependencies.js';
            const fs_data_path = '/data.txt';

            let v = 0;

            const moduleArgs = {
                arguments: [fs_data_path],
                monitorRunDependencies: left => console.log(`left ${left}`),
                preRun: [
                    emsModule => {
                        emsModule.addRunDependency('data');

                        fetch('./data.txt')
                            .then(response => response.arrayBuffer())
                            .then(buffer => {
                                console.log('write file');
                                emsModule.FS.writeFile(fs_data_path, new Uint8Array(buffer));

                                emsModule.removeRunDependency('data');
                            });
                    },
                ],
            };

            await Module(moduleArgs).then(emsModule =>
            {
                v = emsModule._increment(v);
                console.log(`return=${v}`);
            });
        </script>
    </head>
    <body>
    </body>
</html>

C:\wasm\project\12-monitor-dependencies\main.cpp
引数で渡されたファイルを開き内容を標準出力に出力する。

// UTF-8N CRLF
#include <emscripten.h>
#include <iostream>
#include <fstream>

extern "C"
EMSCRIPTEN_KEEPALIVE
int increment(int v)
{
	printf("-- increment(%d)\n", v);
	return v + 1;
}

int main(int argc, char** argv)
{
	std::cout << "C++ main(argc=" << argc << ", argv=[";

	for (int i=0; i<argc; ++i)
	{
		if (i) {
			std::cout << ",";
		}
		std::cout << "'" << argv[i] << "'";
	}

	std::cout << "])" << std::endl;

	std::cout << "open: " << argv[1] << std::endl;
	std::ifstream ifs{ argv[1] };
	if (ifs)
	{
	    std::string line;
    	while (std::getline(ifs, line))
		{
	        std::cout << "DATA: " << line << std::endl;
    	}
	}
	else
	{
		std::cerr << "file open error" << std::endl;
	}

	return 0;
}

// EOF

C:\wasm\project\12-monitor-dependencies\data.txt

1000
1010
2100

実行結果

C++ の main() 関数の実行前に /data.txt が出力されていることが確認できる

left 1
write file
left 0
C++ main(argc=2, argv=['./this.program','/data.txt'])
open: /data.txt
DATA: 1000
DATA: 1010
DATA: 2100
-- increment(0)
return=1

次の記事 では getenv による環境変数の取得を行っている。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?