Open luii opened 6 years ago
Is it that you would like an example to get started ? Or would you like to volunteer to add this ?
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...
An example to get started would be good.
I dont understand it too... i struggle with segmentation fault!
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?
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"]
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?
How to create utf8 string from a argument