背景:我正在尝试创建一个node.js克隆用于演示目的和学习练习。
当我尝试调用我在cavascript中附加到javascript中的对象的回调时,我遇到了一个段错误。我正在使用obj->Set(xxx, callback)
为对象分配值。每当发出http请求时,我都会返回该对象并使用obj->Get(xxx)
来获取该回调并尝试调用它。但是,在使用指针时,我遇到了段错误。
以下是代码:
#include "HttpWrap.h"
#include <cstdlib>
#include "v8/include/v8.h"
#include "libuv/include/uv.h"
using namespace v8;
HttpWrap::HttpWrap(const Arguments& args)
{
Local<ObjectTemplate> serverTemplate = ObjectTemplate::New();
serverTemplate->SetInternalFieldCount(1);
serverTemplate->Set(String::New("listen"), FunctionTemplate::New(Listen));
Local<Object> localServer = serverTemplate->NewInstance();
localServer->SetInternalField(0, External::New(this));
String::AsciiValue ip_address(args[0]);
int port = args[1]->Int32Value();
handle = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
uv_tcp_init(uv_default_loop(), handle);
handle->data = this;
uv_tcp_bind(handle, uv_ip4_addr(*ip_address, port));
server = Persistent<Object>::New(localServer);
}
Handle<Value> HttpWrap::Listen(const Arguments& args)
{
puts("HttpWrap::Listen");
HandleScope scope;
Local<External> wrap = Local<External>::Cast(args.Holder()->GetInternalField(0));
HttpWrap* httpWrap = static_cast<HttpWrap*>(wrap->Value());
httpWrap->server->Set(String::New("onrequest"), args[0]);
uv_listen((uv_stream_t*) httpWrap->handle, 128, OnConnection);
return scope.Close(Undefined());
}
void HttpWrap::OnConnection(uv_stream_t* handle, int status)
{
puts("HttpWrap::OnConnection");
uv_tcp_t* client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
uv_tcp_init(uv_default_loop(), client);
client->data = handle->data;
uv_accept(handle, (uv_stream_t*) client);
uv_read_start((uv_stream_t*) client, AllocConnection, OnRead);
}
uv_buf_t HttpWrap::AllocConnection(uv_handle_t* handle, size_t suggested_size)
{
puts("HttpWrap::AllocConnection");
return uv_buf_init((char*) malloc(suggested_size), suggested_size);
}
void HttpWrap::OnRead(uv_stream_t* server, ssize_t nread, uv_buf_t buf)
{
HandleScope scope;
puts("HttpWrap::OnRead");
HttpWrap* httpWrap = static_cast<HttpWrap*>(server->data);
Local<String> callbackSym = String::New("onrequest");
Local<Value> value = httpWrap->server->Get(callbackSym);
if (!value->IsFunction())
{
puts("Value is not a function");
}
else
{
puts("Value is a function");
Local<Function> callback = Local<Function>::Cast(value);
Local<Value>* argv = new Local<Value>[1];
argv[0] = String::New("test");
puts("Invoking callback");
callback->Call(Context::GetCurrent()->Global(), 1, argv);
puts("invoked callback");
}
free(buf.base);
uv_close((uv_handle_t*) server, OnClose);
}
void HttpWrap::OnClose(uv_handle_t* handle)
{
puts("HttpWrap::OnClose");
}
感兴趣的行是36和65.只要尝试调用callback->Call
,就会发生段错误。
非常感谢任何建议的想法或良好做法!
答案 0 :(得分:1)
不幸的是,在对此进行故障排除时,我有一点隧道视野。主要问题是我在尝试调用回调之前处理主要上下文。由于上下文试图调用js空间中的代码失败。