我想知道下面描述的步骤是如何完成的:
- 如何将 JS 源文件(带有两个函数 funcA() 和 funcB() 的 test.js)转换为字节码?
- 如何将生成的字节码加载到 duktape 中并调用其中一个函数,比如 funcA()?
谢谢。
测试.js:
function funcA() {
print("funcA()");
}
function funcB() {
print("funcB()");
}
主文件
int main() {
duk_context* ctx = duk_create_heap_default();
std::string byteCodeBuff; // buffer where to save the byte code;
{ // generate the bytecode from 'sourceFilePath'
const char* sourceCodeFilePath = "test.js"; // contains the JS code
// Step 1 How to 'dump' the 'sourceFilePath' to bytecode buffer ???
// get the duktape bytecode
duk_size_t bufferSize = 0;
const char* bytecode = (const char*)duk_get_buffer(ctx, -1, &bufferSize);
// save the bytecode to byteCodeBuff
byteCodeBuff.assign(bytecode,bufferSize);
duk_pop(ctx); // bytecode buffer
}
{ // load the bytecode into duktape
const size_t length = byteCodeBuff.size(); // bytecode length
const char* bytecode = &byteCodeBuff.front(); // pointer to bytecode
char* dukBuff = (char*)duk_push_fixed_buffer(ctx, length); // push a duk buffer to stack
memcpy(dukBuff, bytecode, length); // copy the bytecode to the duk buffer
// Step 2 ??? How start using the bytecode
// ??? How to invoke funcA()
// ??? How to invoke funcB()
}
duk_destroy_heap(ctx);
return 0;
}