nodejs / node-addon-api

Module for using Node-API from C++
MIT License
2.15k stars 460 forks source link

Request a c++ call js demo. #1449

Closed CancerQ closed 7 months ago

CancerQ commented 7 months ago

Request a c++ call js demo. I already have some code, but c++ directly calls js code error, I do not know how to modify, can provide some help, the error location in callback.h:46 and 47, example_wrap.cxx:1476 has implemented DefineClass. Here is the code of my js:

class Call extends Callback{
   run(): void {
      console.log("Call Run");
   }
}
let c: Caller = new Caller();
let cb:Call  = new Call();
c.setCallback(cb);
c.call(); // There is an error in this line

I hope I don't want to change the c++ Callback, Caller. Can be modified, SwigDirector, Swig_Callback, and example_wrap.cxx. Because of our need to transfer the existing c++ library out of js interface to use, the following is my c++ code:code.zip

NickNaso commented 7 months ago

Hi @CancerQ in your example there is a lot of code autogenerated by SWIG and for me it's difficult to understand all of it and give you a seuggestion. Could you exaplain you use case so maybe I can try to create an example for you?

CancerQ commented 7 months ago

Hi @CancerQ in your example there is a lot of code autogenerated by SWIG and for me it's difficult to understand all of it and give you a seuggestion. Could you exaplain you use case so maybe I can try to create an example for you?

I have modified my c++ code and it can be used normally. The following is my modified code. So that other people have the same problem in the future. code_adjust.zip

CancerQ commented 7 months ago

Hi @CancerQ in your example there is a lot of code autogenerated by SWIG and for me it's difficult to understand all of it and give you a seuggestion. Could you exaplain you use case so maybe I can try to create an example for you?

The class CallBack in callback.h and the Caller in example.h are our c++ code that we need to convert into code that js can call. The code in example_wrap.cxx is all swig conversion code, and since swig does not support CallBack roll-out, the code in callback.h other than "class CallBack" is the middle-tier code we wrote to use swig. The following js code:

class Call extends Callback{
run(): void {
console.log("Call Run");
}
}
let c: Caller = new Caller();
let cb:Call  = new Call();
c.setCallback(cb);
c.call();  // There is an error in this line

Corresponding to c++ :

class Call : Callback{
Callback();
~Callback()
void run() {
std::cout << "Call Run" << std::endl;
}
}

Caller c = new Caller();
Call cb = new Call();
c->setCallback(cb);
c->call();