在emscripten中将C++函数传递给javascript函数

16

我正在学习emscripten并试图更好地理解它。据我所知,它的主要设计用途是将现有的C / C ++代码移植到Web客户端(浏览器)并从JavaScript调用C / C ++代码。

但我想知道是否可以使用C ++和Emscripten来制作网页(注:这更多是出于好奇心 - 我知道目前没有太多充分的理由这样做)。我成功地从C ++中调用了JavaScript函数,并向它们传递string、int、double等类型的参数。但我缺少的是:从C ++中调用JavaScript函数并传递C或C ++函数作为句柄。因此,以一个简单的例子为例:我该如何用纯C ++编写以下Javascript代码?

var myfun = function() { /* do something meaningful here */ }
document.onload(myfun);
3个回答

8

简短概括:

我写了一个库:js-bind,它可以接受任意数量的参数来轻松实现这一点:

using namespace std::placeholders;
using emscripten::val;

// First find the HTML object to attach the event to
auto clickme_btn = val::global("document").call<val>("getElementById", string("clickme_btn"));

// Bind the event handler for click
auto onclick = [](val event){ cout << "hello world ! " << endl; };
clickme_btn.set("onclick", js::bind(onclick, _1));

这个库是基于下面的宏元编程解释的一些内容。
详细答案:
你有不同的选择,比如emscripten ccall,但我认为更容易使用的是Embind。
例如,从C ++中绑定XMLHttpRequest的事件处理程序。
要启用它,您必须使用以下命令进行编译:--bind -s NO_EXIT_RUNTIME=1 Emscripten:绑定独立函数
可以通过独立函数和单例轻松实现它,如下所示:
#include <iostream>

#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>


namespace xhr {

  inline emscripten::val& singleton() {
    using emscripten::val;
    static val instance = val::global("XMLHttpRequest").new_();
    return instance;
  }

  void on_load(emscripten::val event) { 
    std::cout << "Successful Query " << std::endl;
    std::cout << "response is : " << singleton()["responseText"].as<std::string>() << std::endl;
  }

  void on_error(emscripten::val event) {
    std::cout << "Error on query " << std::endl;
  }

  void on_progress(emscripten::val event) {
    std::cout << "Progress on query " << std::endl;

    std::cout << event["lengthComputable"].as<bool>() << ": " << event["loaded"].as<unsigned int>() / event["total"].as<unsigned int>() << std::endl;
  }


  using namespace emscripten;

  EMSCRIPTEN_BINDINGS(xhr) {
    function("on_load", &on_load);
    function("on_error", &on_error);
    function("on_progress", &on_progress);
  }

}


int main(int argc, char** argv) {

  using emscripten::val;

  xhr::singleton().call<val>("open", std::string("GET"), std::string("http://127.0.0.1:8080/CMakeCache.txt"), true);

  // Here I set the callback to &on_load function registered via the EMSCRIPTEN_BINDINGS macro.
  xhr::singleton().set("onload",val::module_property("on_load"));
  xhr::singleton().set("onprogress",val::module_property("on_progress"));  
  xhr::singleton().set("onerror",val::module_property("on_error"));  

  xhr::singleton().call<val>("send");


  return 0;
}

Emscripten:绑定成员函数

在C++中,我们通常使用std::bind回调函数。采用xhr示例,也可以以更简洁的方式实现:

#include <iostream>
#include <functional>
#include <memory>

#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>

class MiniXhr : public std::enable_shared_from_this<MiniXhr> {
  using val = emscripten::val;
  using url_t = std::string;

  public:

    void set_url(const url_t& url) { url_ = url; }

    void GET();

    /**
     *
     * The member function to be called from javascript.
     */
    void on_readystate(val event) {
      std::cout << "ready " << std::endl;
      std::cout << "xxhr::on_readystate: " 
          << xhr["readyState"].as<size_t>() << " - " << url_ << " :: "
          << xhr["status"].as<size_t>() << ": " 
          << xhr["statusText"].as<std::string>() << std::endl;
    }

  private:
    url_t url_;
    val xhr = val::global("XMLHttpRequest").new_();
};


using emscripten::class_;
EMSCRIPTEN_BINDINGS(MiniXhr) {

  /**
   * Binding for the class.
   */
  class_<MiniXhr>("MiniXhr")
    .smart_ptr<std::shared_ptr<MiniXhr>>("shared_ptr<MiniXhr>")
    .function("on_readystate", &MiniXhr::on_readystate)
    ;

  /**
   * More generic binding to bind a functor with one argument (event handler get the event)
   * Here std::function call operator from C++ is bound to function opcall() in JS.
   */
  class_<std::function<void(emscripten::val)>>("VoidValFunctor")
    .constructor<>()
    .function("opcall", &std::function<void(emscripten::val)>::operator());


}

/**
 *
 * Finally the interesting part : binding the member function on_readystate to the readystatechange event of XMLHttpRequest.
 *
 */

 void MiniXhr::GET() { 

  /**
   * Here this lambda could be put as function in a library, to do an JS(std::bind), 
   * it should just be overloaded for different argument count. (Im on it).
   */
  auto jsbind = [](val& target, const char* property, auto bind_expression ) {

    // Create an std::function from the bind expression
    std::function<void(emscripten::val)> functor = bind_expression;

    // We ensure the correct object will always be bound to the this of the function
    auto functor_adapter = val(functor)["opcall"].call<val>("bind", val(functor)); 

    // Finally we simply set the eventhandler
    target.set(property, functor_adapter);
  };

  // Here we could bind as many member function as we want.

//    jsbind(xhr, "onload", std::bind(&MiniXhr::on_load, shared_from_this(), std::placeholders::_1));
//    jsbind(xhr, "onerror", std::bind(&MiniXhr::on_error, shared_from_this(), std::placeholders::_1));
//    jsbind(xhr, "onprogress", std::bind(&MiniXhr::on_progress, shared_from_this(), std::placeholders::_1));
  jsbind(xhr, "onreadystatechange", std::bind(&MiniXhr::on_readystate, shared_from_this(), std::placeholders::_1));

  // Note that we bind with shared_from_this(), as the scope where the class was instantiated may be dead
  // and only later our callback will come back.

 xhr.call<val>("open", std::string("GET"), url_, true);
 xhr.call<val>("send");
}


int main(int argc, char** argv) {


  auto x = std::make_shared<MiniXhr>();
  x->set_url("notfound.json");
  x->GET();

  return 0;
}

到目前为止,这是最好的答案...谢谢。 - Joma
嗨@daminetreg,感谢您的示例。我可以将其用于多个请求吗?或者一个请求可以将响应发送到其他程序部分中的其他绑定吗? - Paulo Coutinho
原则上,您可以实例化多个MiniXhr,它也可以工作。但是我建议您使用我编写的库xxhr,它可以在WebAssembly中工作,并允许解耦不同的回复/响应:https://nxxm.github.io/xxhr/html/index.html - daminetreg

1

这是我很久以前在使用Emscripten编写C代码时使用的一些东西:

void myfun(void(*f)(void)) { (*f)() }

然后这里会是JavaScript代码:

var theparty = Runtime.addFunction(function() { print("Will there be confetti?") });
Module.ccall("myfun", "number", ["number"], [theparty]);
Runtime.removeFunction(theparty); // output => Will there be confetti?

我总是在执行后移除不再需要的函数,以保留内存。这是使代码片段无缝协作的简单方法。你可以很明显地修改它来做任何你想要的事情,而不仅仅是打印信息。 :P

0

我对emscripten不太确定,但总的来说,我理解你需要知道如何将C++函数作为句柄传递给另一个C++函数。希望我能帮到你。

JavaScript、PHP和其他更灵活的语言允许通过函数对象进行传递。在C和C++中,略有不同,你必须将函数指针作为参数传递给其他函数。在C中,这个名字叫做回调(Callback),而不是句柄。

例如:

/* This function takes a single callback as a parameter. */
//here we say that the parameter, that we name numberSource, is a function that receives no parameters itself (void), and return an int
void printNumber(int (*numberSource)(void)) {
    printf("%d", numberSource());
}

/* A possible callback */
int oneExampleFunction(void) {
    return 100;
}

/* Another possible callback. */
int otherExampleFunction(void) {
    return 200;
}

/* This is how we would call printNumber with three different callbacks. */

//with "&" we are referencing the memory address of the function, 
//since thats what printNumber is expecting
printNumber(&oneExampleFunction);
printNumber(&otherExampleFunction);
printNumber(&rand); //where are using rand(), a system function, that works as well. 

通常的做法是创建一个自定义类型来作为参数,这样你就不需要使用像 int (*numberSource)(void) 这样丑陋的东西了。它会是类似于:

//Function pointer called CallbackType that takes a float
//and returns an int
typedef int (*NameYouWantForTheType)(void);  

因此,printNumber函数应该像这样:

void printNumber(NameYouWantForTheType numberSource ) {
    printf("%d", numberSource());
}

所以,在你的情况下, 如果你想要翻译这段JS代码

var myfun = function() { /* do something meaningful here */ }
document.onload(myfun);

转换成C语言后,你会有一个名为“document”的C对象,它接收执行某些其他操作的函数,你的C代码将如下所示:

void myfun (void) {
  /* do something meaningful here */
}

document.onload(&myfun);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接