ScriptingCore::getInstance()->evalString可以有返回值么

ScriptingCore::getInstance()->evalString可以有返回值么?js端的函数返回bool,但在oc端一直返回true呢?

// outVal 是js函数的返回值,这里我们可以不管它
jsval *outVal;
// OC调用JS,传回商品ID
ScriptingCore::getInstance()->evalString(stringFunc, outVal);

如果是bool值的话,这个outVal应该怎么定义呢?

  • will eval the specified string
    • @param string The string with the javascript code to be evaluated
    • @param outVal The jsval that will hold the return value of the evaluation.
    • Can be NULL.
      */
      bool evalString(const char *string, jsval outVal, const char filename = NULL, JSContext cx = NULL, JSObject global = NULL);

#import “js_manual_conversions.h”

ScriptingCore* sc = ScriptingCore::getInstance();
JSContext* cx = sc->getGlobalContext();
jsval outVal;
sc->evalString(“cc.find(‘Game’).getComponent(‘Player’).onBeforeWillEnterForeground();”, &outVal);
int val;
jsval_to_int(cx,outVal,&val);//为什么提示错误:no matching function to call jsval_to_int呢?

@jare

官方的技术达人可以帮忙解答下么?

evalString 的 bool 返回值表示是否执行成功,并不是 JS 代码的返回值。

outVal 才是返回值,但是你这里定义有问题,需要定义成:

auto cx = ScriptingCore::getInstance()->getGlobalContext();
JS::RootedValue outVal(cx);
ScriptingCore::getInstance()->evalString(stringFunc, &outVal);

int val;
jsval_to_int(cx, outVal, &val);

总的来说是你的 outVal 的类型有问题,需要用 rooted 类型,不能用直接类型。
参考这个文档: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/GC_Rooting_Guide

感谢panda大神百忙之中的解答,第一次接触这个知识点,把论坛的帖子都搜了一遍,我试试看看,万分感谢:)

ScriptingCore::getInstance()->evalString(stringFunc, &outVal);
这行报错:cannot initialize a parameter of type jsval * with a rvalue of js::rootedvalue *。

(1)Use an explicit address-of-operator on JS::Rooted to get a JS::MutableHandle.
根据这句话的意思,&outVal就变成JS::MutableHandle了吧?但是evalstring接收的参数是jsval,是不是类型不匹配了呢?
(2)Use JS::MutableHandle typedefs for function out-parameters.
根据这句话的意思,evalString函数的第二个参数的类型是不是应该是JS::MutableHandleValue?

在AppController.mm中的代码片段。

你用的还是 1.2 吧?我写的是 1.3 的接口,最好升级一下

嗯,我用的1.2.2beta2,刚才升级到了1.3.0rc1:
(1)在模拟器下打开任何场景,都直接启动了launch场景。
(2)而且运行到需要切换场景的时候直接闪退,launch场景设置的是点击或到5秒后切换到主场景。

主菜单:项目->项目设置->预览运行

可能这里设置了launch场景,所以不管当前是什么场景都会启动这一个

切换场景时闪退,是模拟器闪退还是编辑器闪退?有没有报错信息?

是cc.audioEngine.end函数的问题,把这个注释掉就可以了,只是控制台没有提示,自己猜的,注释掉就可以了

谢谢反馈 @visualsj

更新到1.3.0rc1后,按照panda的指点,可以拿到返回值啦,谢谢:)

ScriptingCore::getInstance()->evalString(stringFunc, outVal);这个方法我用不了

有什么错误提示么

报这个错。NO mathching member function for call to ‘evalString’

哪个版本的

上面的可以。下面这个就报错