[英]Load native C modules in duktape 2.1.0 to
I am still lost after reading the how-to article. 阅读操作方法文章后,我仍然迷失了方向。
It is said that 据说
The load callback is a Duktape/C function which takes the resolved module ID and: (1) returns the Ecmascript source code for the module or undefined if there's no source code, eg for pure C modules, (2) can populate module.exports itself, and (3) can replace module.exports.
加载回调是一个Duktape / C函数,它使用已解析的模块ID,并且:(1)返回该模块的Ecmascript源代码,或者如果没有源代码(例如,纯C模块的源代码)则为undefined,(2)可以填充module.exports本身,并且(3)可以替换module.exports。
But when loading a native C module, 但是在加载本机C模块时,
duk_push_undefined(ctx)
instead of duk_push_string(ctx, module_source)
? duk_push_undefined(ctx)
而不是duk_push_string(ctx, module_source)
吗? return 0
instead of return 1
? return 0
而不是return 1
? I tried to call myobject_init
(using the default instance in http://wiki.duktape.org/HowtoNativeConstructor.html ) in the load callback cb_load_module
. 我试图在加载回调
cb_load_module
调用myobject_init
(使用http://wiki.duktape.org/HowtoNativeConstructor.html中的默认实例)。 But duktape complains 但是duktape抱怨
TypeError: [object Object] not constructable
TypeError:[object Object]无法构造
when I evaluate var MyObject = require("MyObject")
, no matter if I 当我评估
var MyObject = require("MyObject")
,无论我
Problem solved. 问题解决了。 There are a few more details scattered in
还有一些细节分散在
The most important tricks are: 最重要的技巧是:
The module init function should return a function (constructor is also a function). 模块的初始化函数应该返回一个函数(构造函数也是一个函数)。 Do NOT register the function using
duk_put_global_string
. 不要使用
duk_put_global_string
注册该函数。
duk_ret_t module_init(duk_context* ctx) { duk_push_c_function(ctx, module_constructor, num_arguments_for_constructor); // set properties for the constructor return 1; // stack: [ ... constructor ] }
The function cb_load_module
must push the module init function into the value stack, then use duk_call
to call it and set module.exports
. 函数
cb_load_module
必须将模块init函数推入值堆栈,然后使用duk_call
进行调用并设置module.exports
。 Do NOT call the module init function directly. 不要直接调用模块初始化函数。
duk_ret_t cb_load_module(duk_context *ctx) { // stack: [ resolved_id exports module ] ... duk_push_c_function(ctx, module_init, 0); duk_call(ctx, 0); duk_put_prop_string(ctx, 2, "exports"); // obj_idx(module) = 2 return 0; // no .js source for native modules }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.