简体   繁体   中英

Wrapping a C++ Member Function Pointer (Emscripten)

I would like to create a wrapper around a C++ member function, which does some additional tasks before calling the actual member function. I'm working with Emscripten and my example below is using the .function function .

Let's say I have a class called SomeClass (which I don't "own", ie it's coming from a third party library) with a single static member function:

class SomeClass {
public:
  void test(int& number) {
    number++;
  }
};

Normally, I would create Emscripten bindings with Embind like this:

class_<SomeClass>("SomeClass")
  .function("test", 
    &SomeClass::test
  )
;

However, I would like to use a wrapper around that method, like this (C++ - JS - Pseudo-Code)

class_<SomeClass>("SomeClass")
  .function("test", 
    &((this) => {
      int i = 0;
      this->test(i);
    })
  )
;

Is that somehow possible? Any help would be greatly appreciated!

I figured it out. Emscripten seems to be design with such a use-case in mind and offers a specialization of the RegisterClassMethod struct for std::function .

Using the following code, I can achieve what I want to do.

class_<SomeClass>("SomeClass")
  .function("test", std::function<void(SomeClass&)>([](SomeClass& s) {
    int i = 0;
    s.test(i);
  }))
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM