Duktape是款比较小巧的JavaScript引擎,适用于嵌入式系统,不过API使用不太方便,研究了两天决定放弃。下面把测试代码上来,做个备忘吧。
duktape_helper.hpp文件
#ifndef DUKTAPE_HELPER_HPP
#define DUKTAPE_HELPER_HPP
#include <memory>
#include <string>
#include <type_traits>
#include "duktape.h"
namespace duktape {
class StackAssert {
private:
duk_context *m_context;
unsigned m_expected;
unsigned m_begin;
public:
/**
* Create the stack checker.
*
* No-op if NDEBUG is set.
*
* \param ctx the context
* \param expected the size expected relative to the already existing values
*/
inline StackAssert(duk_context *ctx, unsigned expected = 0) noexcept
: m_context(ctx)
, m_expected(expected)
, m_begin(static_cast<unsigned>(duk_get_top(ctx)))
{
}
/**
* Verify the expected size.
*
* No-op if NDEBUG is set.
*/
inline ~StackAssert() noexcept
{
if (static_cast<unsigned>(duk_get_top(m_context)) - m_begin != m_expected) {
std::fprintf(stderr, "Corrupt stack detection in StackAssert:\n");
std::fprintf(stderr, " Size at start: %u\n", m_begin);
std::fprintf(stderr, " Size at end: %d\n", duk_get_top(m_context));
std::fprintf(stderr, " Expected (user): %u\n", m_expected);
std::fprintf(stderr, " Expected (adjusted): %u\n", m_expecte