nodejs / node-addon-examples

Node.js C++ addon examples from http://nodejs.org/docs/latest/api/addons.html
Other
2.49k stars 600 forks source link

Need example of napi_get_value_string_utf8 #83

Open luii opened 6 years ago

luii commented 6 years ago

How to create utf8 string from a argument

mhdawson commented 6 years ago

Is it that you would like an example to get started ? Or would you like to volunteer to add this ?

Globik commented 6 years ago

I'm also intrested in this method api. I shall do my best. Trying to give req.header["user-agent"] to the c native code : ) By the way, nullptr on C code kinda undeclared. One need NULL or ((void*)0) to write...

JamesRamm commented 6 years ago

An example to get started would be good.

Misery42 commented 5 years ago

I dont understand it too... i struggle with segmentation fault!

Misery42 commented 5 years ago

JS

var sRes = addon.helloWorld("hello", "world");
console.log(`helloWorld returned: ${sRes}`);

C Code:

napi_value hello_world (napi_env env, napi_callback_info info) {

  size_t argc = 2;

  napi_value args[2];

  napi_get_cb_info(env, info, &argc, args, NULL, NULL);

  size_t str_size;
  size_t str_size_read;
  napi_get_value_string_utf8(env, args[1], NULL, 0, &str_size);
  char * buf;
  buf = (char*)calloc(str_size + 1, sizeof(char));
  str_size = str_size + 1;
  napi_get_value_string_utf8(env, args[1], buf, str_size, &str_size_read);

  printf("%s, %s \n", "Hello", buf); // output: Hello, world

  napi_value result;

  napi_create_string_utf8(env, buf, str_size_read, &result);
  free(buf);
  return result;
}

Output: helloWorld returned: worl However one char "d" is missing any idea?

Misery42 commented 5 years ago

Note! str_size = str_size + 1;

["w", "o", "r", "l", "d", "NULL"] In this case str_size is 5! But when you want to fill the buffer you need a size of 6! Otherwise your string got truncated to ["w", "o", "r", "l", "NULL"]

mhdawson commented 5 years ago

Believe you can also use NAPI_AUTO_LENGTH if it is NULL terminated and you don't want to specify the size

@Misery42 any chance you want to submit a PR for an example covering this?