1

I want to call a method written in C++ from a Javascript code passing a string argument. The solution I find is to use Node.js and SWIG to generate bindings.

I followed the example from here (see enobayram post): How can I use a C++ library from node.js?

The C++ method looks like:

Handle<Value> CMyClass::Open(const v8::Arguments& args)
{
 HandleScope scope;

 std::string port(*v8::String::Utf8Value(args[0]));
 std::cout << port << std::endl;

 return scope.Close(Undefined());
}

From Node.js console:

var toto = require("./build/Release/MyClass")

var c = new toto.CMyClass()

c.Open("test")
Error: in method 'CMyClass_Open', argument 2 of type 'v8::Arguments const &'
    at repl:1:4
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.EventEmitter.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)

Any ideas ? Thanks a lot

Community
  • 1
  • 1

1 Answers1

1

In your swig_wrapper.i (or mylib.i in the example), add %include "std_string.i" just before the line %include myclass.h and rerun swig again.

Citation: http://www.swig.org/Doc1.3/Library.html#Library_stl_cpp_library

std::deque      std_deque.i
std::list       std_list.i
std::map        std_map.i
std::pair       std_pair.i
std::set        std_set.i
std::string     std_string.i
std::vector     std_vector.i

C++ Example:

/* C++ --> JavaScript */
std::string testOut() {
    return "Hello World!";
}

/* JavaScript --> C++ */
void testIn(std::string args) {
    std::cout << "Result: " << args << std::endl;
}
TekuConcept
  • 1,264
  • 1
  • 11
  • 21