我试图通过捕获函数入口和出口来实现一个简单的QtScript性能分析器。QScriptEngineAgent
我成功订阅了QScriptEngineAgent::functionEntry()
回调。现在,是否可以在此回调中获取正在调用的函数的名称(作为字符串)?
尽管我知道并非所有脚本函数都需要有一个名称,即使在最简单的情况下它似乎也不起作用。QScriptContextInfo
为此提供了便利,但它似乎失败了。然后我试图获得arguments.callee.name
财产的价值,但它也失败了。
这是我尝试实现它的粗略概述,我试图在 qt-5.3.2/linux 上运行它。
tmp.pro
:
TEMPLATE = app
TARGET = tmp
INCLUDEPATH += .
QT += core script
SOURCES += main.cpp
main.cpp
:
#include <QCoreApplication>
#include <QScriptEngine>
#include <QScriptEngineAgent>
#include <QScriptContextInfo>
#include <QDebug>
class MyAgent: public QScriptEngineAgent {
private:
void functionEntry(qint64 scriptId) {
qDebug() << "functionEntry" << scriptId;
QScriptContext *context = engine()->currentContext();
// QScriptContextInfo should have function name, by design, afaik
QScriptContextInfo contextInfo(context);
qDebug() << contextInfo.functionName();
// probably my typical js-side arguments.callee.name would work?
QScriptValue callee = context->callee();
qDebug() << callee.property("name").toString();
// function.toString() should have at least something (?)
qDebug() << callee.toString();
// hmm. what's our context, anyway?
qDebug() << context->toString();
}
public:
MyAgent(QScriptEngine *eng) : QScriptEngineAgent(eng) {
qDebug() << "engine" << eng;
}
};
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
QScriptEngine eng;
MyAgent agent(&eng);
eng.setAgent(&agent);
qDebug() << "agent " << eng.agent();
eng.evaluate("function foo() { return 6 * 7; }"
"function bar() { return foo(); }");
QScriptValue bar = eng.globalObject().property("bar");
// See? Here the callee is printed as expected.
qDebug() << "call " << bar.property("name").toString() << bar.toString();
QScriptValue ret = bar.call();
qDebug() << "answer" << ret.toNumber();
return 0;
}
输出样本,我不满意,因为我希望看到“foo”和“bar”而不是一些空字符串:
engine QScriptEngine(0x7fffc55c4560)
agent 0x7fffc55c4570
functionEntry 140300485581200
""
""
""
"<global>() at -1"
functionEntry -1
""
""
""
"<global>() at -1"
call "bar" "function bar() { return foo(); }"
functionEntry 140300485581200
""
""
""
"<global>() at -1"
functionEntry 140300485581200
""
""
""
"<global>() at -1"
answer 42