200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 树莓派js调用C语言 SpiderMonkey js中调用c程序

树莓派js调用C语言 SpiderMonkey js中调用c程序

时间:2023-09-20 12:49:35

相关推荐

树莓派js调用C语言 SpiderMonkey js中调用c程序

原理: 通过JS_DefineFunctions函数, 向js注册函数.

1.添加头文件, 并定义宏

#include

#include

#include

#include

#define LOG_MINARGS 0

2.定义一个c函数

JSBool logging(JSContext *ConText, JSObject *object, uintN argc, jsval *argv, jsval *value)

{

JSString *jss;

int i = 0;

for(i=0; i

{

jss = JS_ValueToString(ConText, argv[i]);

printf("message: %s\n", JS_GetStringBytes(jss));

}

return JS_TRUE;

}

3.定义一个函数表

JSFunctionSpec Functions[] = {

{"logging", logging, LOG_MINARGS, 0, 0},

{0,0,0,0,0}

};

4.添加主函数

int main(int argc, char **argv)

{

JSRuntime *RunTime = NULL;

JSContext *ConText = NULL;

JSObject *Global = NULL;

jsval rval;

const char *Script;

if(argc != 2)

{

printf("入参个数错误\n");

return 0;

}

Script = argv[1];

printf("script is \"%s\"\n", Script);

if(!(RunTime = JS_NewRuntime(1024L * 1024L)) || !(ConText = JS_NewContext(RunTime, 8192)) || !(Global = JS_NewObject(ConText, NULL, NULL, NULL)))

{

return EXIT_FAILURE;

}

if(!JS_InitStandardClasses(ConText, Global))

{

return EXIT_FAILURE;

}

//向javascript中注册函数

if(!JS_DefineFunctions(ConText, Global, Functions))

{

return EXIT_FAILURE;

}

if(!JS_EvaluateScript(ConText, Global, Script, strlen(Script), "script", 1, &rval))

{

return EXIT_FAILURE;

}

printf("the script's result is %d\n", JSVAL_TO_INT(rval));

JS_DestroyContext(ConText);

JS_DestroyRuntime(RunTime);

JS_ShutDown();

return EXIT_SUCCESS;

}

5.编译代码

gcc -o examle examle.c -L$HOME/local/normal/lib -ljs

6.运行程序

./examle "var a=6; var b=11; function add(a,b){return a+b}; console={}; console.log=logging; console.log(a,b,add(a,b)); add(a,b)"

7.执行结果

script is "var a=6; var b=11; function add(a,b){return a+b}; console={}; console.log=logging; console.log(a,b,add(a,b)); add(a,b)"

message: 6

message: 11

message: 17

the script's result is 17

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。