ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

有没有办法在JavaScript中使用C?

2019-08-24 22:38:29  阅读:185  来源: 互联网

标签:javascript c cross-platform


this开始,我发现JavaScript是用C语言编写的.我也发现/推断出大部分JavaScript都是C(例如Math.atan“”和Math.atan.toString()让人产生的函数atan(){[native code]}“). [本机代码我假设是C,否则“隐藏”它的意义何在?

我的问题是有一种在JavaScript中使用C的方法吗?要在函数或JavaScript平台中使用它吗?

解决方法:

emscripten项目允许您从C和C生成Javascript:

Emscripten is an LLVM-to-JavaScript compiler. It takes LLVM bitcode –
which can be generated from C/C++, using llvm-gcc (DragonEgg) or
clang, or any other language that can be converted into LLVM – and
compiles that into JavaScript, which can be run on the web (or
anywhere else JavaScript can run).

通过像ccall and cwrap这样的方法你可以调用C函数:

使用站点中的示例,此C代码使用extern“C”来防止名称重写:

#include <math.h>

extern "C" {

int int_sqrt(int x) {
  return sqrt(x);
}

}

可以像这样编译:

./emcc tests/hello_function.cpp -o function.html -s EXPORTED_FUNCTIONS="['_int_sqrt']"

并在Javascript中使用:

int_sqrt = Module.cwrap('int_sqrt', 'number', ['number'])
int_sqrt(12)
int_sqrt(28)

embind可用于C函数和类.该网站的简单示例如下:

// quick_example.cpp
#include <emscripten/bind.h>

using namespace emscripten;

float lerp(float a, float b, float t) {
    return (1 - t) * a + t * b;
}

EMSCRIPTEN_BINDINGS(my_module) {
    function("lerp", &lerp);
}

并编译:

emcc --bind -o quick_example.js quick_example.cpp

并在Javascript中使用:

<!doctype html>
<html>
  <script src="quick_example.js"></script>
  <script>
    console.log('lerp result: ' + Module.lerp(1, 2, 0.5));
  </script>
</html>

标签:javascript,c,cross-platform
来源: https://codeday.me/bug/20190824/1712672.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有