WebAssembly js 调用c++ 高性能传参
通过 Emscripten,你可以直接使用 JavaScript 的 TypedArray 与 C++ 共享内存,
从而避免频繁的数据拷贝操作。TypedArray 是一种高效的二进制数据表示形式,非常适合处理大规模数值数据。
js 调用:
cpp
function processDataPointer(inputArray) {
// Create a Float32Array in JavaScript
const data = new Float32Array(inputArray);
const length = data.length;
console.time("processDataPointer");
// Allocate memory in WebAssembly
const dataPtr = Module._malloc(data.byteLength);
// Copy data from JavaScript to WebAssembly memory
Module.HEAPF32.set(data, dataPtr / data.BYTES_PER_ELEMENT);
console.timeEnd("parper data");
Module._processDataPointer(dataPtr, length);
// Free the allocated memory
Module._free(dataPtr);
console.timeEnd("processDataPointer");
}
c++
cpp
#include <iostream>
#include <vector>
#include <cmath>
#include <limits>
#include <emscripten/emscripten.h>
int main()
{
std::cout << "hello" << std::endl;
return 0;
}
extern "C"
{
EMSCRIPTEN_KEEPALIVE
void processDataPointer(float *data, int length)
{
double x{};
double y{};
double z{};
// 假设输入的长度总是 3 的倍数
for (int i = 0; i < length; i += 3)
{
x += data[i + 0];
y += data[i + 1];
z += data[i + 2];
}
}
}
cmakeList:
sh
cmake_minimum_required(VERSION 3.19)
project(obb)
# 默认是Release,如果需要Debug环境,可以在生成时指定 -DCMAKE_BUILD_TYPE=Debug
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
set(CMAKE_CXX_STANDARD 11)
# include_directories(./include/)
file(GLOB SOURCE_FILES src/main.cpp)
file(GLOB HEADER_FILES src/*.h)
add_executable(${CMAKE_PROJECT_NAME} ${SOURCE_FILES} ${HEADER_FILES})
target_link_libraries(${CMAKE_PROJECT_NAME})
if(CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0") # 关闭优化
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s WASM=1 -g -s MODULARIZE=1 -s EXPORT_NAME=createModule -s EXPORTED_FUNCTIONS=_processDataPointer,_malloc,_free -s INITIAL_MEMORY=128MB")
endif()