在JS中,我应该在哪里定义emscripten extern函数

Where should I defined emscripten extern functions in JS?

本文关键字:定义 emscripten extern 函数 在哪里 我应该 JS      更新时间:2023-09-26

假设C++中的函数x定义为:

extern "C" void x();

我在全局上下文中的JS中实现了它

function _x() { console.log('x called'); }

_x是在asm编译的js文件中定义的,该文件正在被调用,而不是我的实现。我做错了什么?

链接时收到此警告:

warning: unresolved symbol: x

这是堆叠竞赛:

Uncaught abort() at Error
at jsStackTrace (http://localhost/module.js:978:13)
at stackTrace (http://localhost/module.js:995:22)
at abort (http://localhost/module.js:71106:25)
at _x (http://localhost/module.js:5829:46)
at Array._x__wrapper (http://localhost/module.js:68595:41)
at Object.dynCall_vi (http://localhost/module.js:68442:36)
at invoke_vi (http://localhost/module.js:7017:25)
at _LoadFile (http://localhost/module.js:7573:6)
at asm._LoadFile (http://localhost/module.js:69219:25)
at eval (eval at cwrap (http://localhost/module.js:554:17), <anonymous>:6:26)

如在Javascript中实现一个C API中所述,通过使用一个Javascript文件来定义一个库,该文件调用mergeInto以将带有Javascript函数的对象合并到LibraryManager.library中。然后使用--js-library选项进行编译,以传递库的位置。

例如,您可以使用带有单个函数库的Javascript文件

// In library.js
mergeInto(LibraryManager.library, {
  x: function() {
    alert('hi');
  },
});

调用此函数的主C++文件

// in librarytest.cc
extern "C" void x();
int main()
{
  x();
  return 0;
}

并使用编译为HTML和Javascript

em++ librarytest.cc --js-library library.js -o librarytest.html

然后在浏览器中加载librarytest.html,它将显示一个带有hi的警告框。

如果您想将字符串从C++传递到Javascript,您不必走在Javascript中实现C API的路线。相反,您可以使用EM_ASM*宏直接内联Javascript。然后,它可以调用您定义的Javascript函数,并传递它们的值。

此外,要传递字符串,您需要确保传递C样式的字符串,然后对结果使用Emscripten提供的Pointer_stringifyJavascript函数:

#include <string>
#include <emscripten.h>
int main()
{
  std::string myString("This is a string in C++");
  EM_ASM_ARGS({
    console.log(Pointer_stringify($0));
  }, myString.c_str());
  return 0;
}