原理: 通过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