문제

I have the following javascript code as string

std::string script = " { function execute() { var x=10; return x; } } ";

I want to evaluate this script and return the value , is there any way to do this?

Thanks in advance.

도움이 되었습니까?

해결책

To evaluate a JS script you will need

JSBool JS_EvaluateScript(JSContext *cx, JSObject *obj, const char *src, uintN length, const char *filename, uintN lineno, jsval *rval);

As described here : https://developer.mozilla.org/en-US/docs/SpiderMonkey/JSAPI_Reference/JS_EvaluateScript

Then if you want to get the returned value you have to call the exectue function :

"function execute(){ var x = 10; return x;} execute();"

Then to evaluate the script have to be a const char* type not a std::string

After evaluating the script you can get the returned value using rval

if(JSVAL_IS_INT(rval))
  printf("The returned value is : %d\n", JSVAL_TO_INT(rval));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top