【发布时间】:2021-07-15 05:41:46
【问题描述】:
以下结果显示两个相同的字符串指针具有不同的值。
为什么?
v8::String::Utf8Value 只是给出它的字符串成员,见https://v8docs.nodesource.com/node-0.8/d4/da0/v8_8h_source.html#l01286
#include <nan.h>
#include <string>
NAN_METHOD(Print) {
Nan::MaybeLocal<v8::String> maybeString = Nan::To<v8::String>(info[0]);
if (maybeString.IsEmpty() == false) {
v8::Local<v8::String> str = maybeString.ToLocalChecked();
char *ptr = *v8::String::Utf8Value(info.GetIsolate(), str);
printf("string %s\n", *v8::String::Utf8Value(info.GetIsolate(), str));
printf(" %s\n", ptr);
printf("ptr %p\n", *v8::String::Utf8Value(info.GetIsolate(), str));
printf(" %p\n", ptr);
printf("ptr %p\n", (char *)*v8::String::Utf8Value(info.GetIsolate(), str));
printf(" %p\n", (char *)ptr);
printf("string %s\n", (char *)*v8::String::Utf8Value(info.GetIsolate(), str));
printf(" %s\n", (char *)ptr);
}
}
NAN_MODULE_INIT(Init) {
Nan::Set(target, Nan::New("print").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(Print)).ToLocalChecked());
}
NODE_MODULE(myaddon, Init);
info[0]='hello world' 的结果:
string hello world
�AZ
ptr 0x65a4140
0x65a4140
ptr 0x65a4140
0x65a4140
string hello world
�AZ
【问题讨论】:
-
通常当您指向的对象被销毁时会发生这种情况,因此指针不再指向相同的数据。如果您在函数中返回指向局部变量的指针,就会发生这种情况。