Coder Social home page Coder Social logo

demo-webassembly's Introduction

简介

2012年,Mozilla 的工程师 Alon Zakai 在研究 LLVM 编译器时突发奇想:许多 3D 游戏都是用 C / C++ 语言写的,如果能将 C / C++ 语言编译成 JavaScript 代码,它们不就能在浏览器里运行了吗?众所周知,JavaScript 的基本语法与 C 语言高度相似。

于是,他开始研究怎么才能实现这个目标,为此专门做了一个编译器项目 Emscripten。这个编译器可以将 C / C++ 代码编译成 JS 代码。

参考文章:

  1. https://developer.mozilla.org/en-US/docs/WebAssembly/Concepts
  2. https://www.ibm.com/developerworks/cn/web/wa-lo-webassembly-status-and-reality/index.html
  3. https://kripken.github.io/emscripten-site/docs/getting_started/downloads.html
  4. https://github.com/mbasso/asm-dom(c++实现简版vdom)

编译c++代码

c++代码在helloworld.cpp里

直接编译

emcc helloworld.cpp -o helloworld.js

容器内编译

docker run \
  --rm \
  -v $(pwd):/src \
  -u $(id -u):$(id -g) \
  emscripten/emsdk \
  emcc helloworld.cpp -o helloworld.js

运行

运行JS

直接使用node或者服务器运行html都可以

node helloworld.js

结果

42

运行wasm

fetch('./helloworld.wasm').then(response =>
  response.arrayBuffer()
).then(buffer =>{
  return WebAssembly.compile(buffer)
}).then(module =>{
  return WebAssembly.instantiate(module, importObject)
}).then(instance => {
  debugger
  console.log('instance.exports.main() :>> ', instance.exports.main());
});

demo-webassembly's People

Contributors

kristenxu avatar

Stargazers

horizon avatar xiaoyi avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.