简体   繁体   English

将duktape 2.1.0中的本机C模块加载到

[英]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模块时,

  • what should be pushed into the value stack? 应该把什么推入价值栈? duk_push_undefined(ctx) instead of duk_push_string(ctx, module_source) ? duk_push_undefined(ctx)而不是duk_push_string(ctx, module_source)吗?
  • what should be returned by the load callback to its caller? 加载回调应返回给调用者什么? 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") ,无论我

  • push undefined into the value stack and return 1, 将undefined推入值堆栈并返回1
  • or push nothing into the value stack and return 0. 或不将任何内容推入值堆栈并返回0。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM