用C++对Duktape JavaScript引擎的简单封装。

本文记录了对Duktape JavaScript引擎的简单封装过程,Duktape适合嵌入式系统,但API使用相对不便。作者分享了测试代码,包括duktape_helper.hpp、main.cpp和CMakeLists.txt,作为备忘。此外,还提及了v7和SpiderMonkey 1.8作为替代选项,对于嵌入式系统,v7足够,而SpiderMonkey虽然文档齐全,但体积较大。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值