0

Im very new to making C++ addons for node.js

So my Question is: Is there a way for an addon-function to return a String? And if so, How? Further Explaining:

Lets say i have a string called std::string testString in my C++ Source File. When given following JS code:

const myAddon = require('path'); console.log(myAddon.myFunc());

It should output the data testString holds.

Sorry if something isnt understandable, this is my first Question here.

Edit: const char* myChar = "Hello World"; would also be okay. Top Priority is to send any kind of Text.

5
  • 1
    Does this answer your question? How do I use std::string in a C++ Addon for Node.js? Commented Aug 10, 2020 at 19:11
  • @Botje it kind of helped, but i want to understand how it works too. So a Simple Showcase of Logging the ancient "Hello World" to the console would be the best. Still thanks for the afford of replying :) Edit: The If Statements and other functions used there confuse me what is actually needed, and what is only there bc of the Question-Authors Goal. Thats the Point im trying to make Commented Aug 11, 2020 at 7:51
  • Returning a string from a function in a C++ addon is the hello world in the documentation. Did you try following that? What did not work? Commented Aug 11, 2020 at 8:03
  • @Botje Logging Text as const char* does work perfectly fine: args.GetReturnValue().Set(String::NewFromUtf8(isolate, myChar).ToLocalChecked()); where myChar is type const char*. Doing this directly with std::string doesnt work ofcourse. But atleast i can now send text to my js file, Thanks! Commented Aug 11, 2020 at 8:22
  • See std::string::c_str() to get a const char * out of a std::string Commented Aug 11, 2020 at 8:24

1 Answer 1

0

Here is an adapted version of the hello world example in the documentation:

#include <node.h>
#include <string>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

std::string testString; // value is set elsewhere.

void MyFunc(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(
      isolate, testString.c_str()).ToLocalChecked());
}

void Initialize(Local<Object> exports) {
  // this would be a good spot to set testString
  NODE_SET_METHOD(exports, "myFunc", MyFunc);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.