node-addon-examples icon indicating copy to clipboard operation
node-addon-examples copied to clipboard

Need example of napi_get_value_string_utf8

Open luii opened this issue 8 years ago • 9 comments

How to create utf8 string from a argument

luii avatar Dec 10 '17 20:12 luii

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

mhdawson avatar Dec 13 '17 22:12 mhdawson

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...

Globik avatar Dec 25 '17 18:12 Globik

An example to get started would be good.

JamesRamm avatar Feb 16 '18 08:02 JamesRamm

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

Misery42 avatar Aug 05 '19 13:08 Misery42

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 avatar Aug 05 '19 14:08 Misery42

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"]

Misery42 avatar Aug 05 '19 17:08 Misery42

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?

mhdawson avatar Aug 14 '19 18:08 mhdawson

Any examples yet? I'm lost.

Zipdox avatar Mar 14 '21 22:03 Zipdox

I deciphered the dead PR mentioned above and here is my code:

char *client_name;
size_t str_size;    
napi_get_value_string_utf8(env, argv[0], NULL, 0, &str_size);
str_size += 1;

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

// Print the final string
printf("client_name: %.*s\n", str_size, client_name);

Zipdox avatar Mar 14 '21 23:03 Zipdox