码迷,mamicode.com
首页 > 编程语言 > 详细

C++调用JS,可变参模板实现,方便调用

时间:2015-07-06 01:28:35      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:c++   js   crossplatform   

#include "scripting/js-bindings/manual/ScriptingCore.h"

#include <sstream>
#include <type_traits>

/// args push helper

template<typename _Ty> inline
void jsx_unpack_arg(std::stringstream& ss, int& carg, const _Ty& arg)
{ // template adapter: must be numeric type
    static_assert(std::is_integral<_Ty>::value || std::is_floating_point<_Ty>::value, "error, jsx_unpack: unsupported type!");
    ss << arg << ",";
    ++carg;
}

inline
void jsx_unpack_arg(std::stringstream& ss, int& /*carg*/)
{ // empty arg
}

inline
void jsx_unpack_arg(std::stringstream& ss, int& carg, const char* arg)
{ // numbers
    ss << "\"" << arg << "\"" << ",";
    ++carg;
}

inline
void jsx_unpack_arg(std::stringstream& ss, int& carg, const std::string& arg)
{
    ss << "\"" << arg << "\"" << ",";
    ++carg;
}

template<typename _Ty, typename..._Args> inline
void jsx_unpack_arg(std::stringstream& ss, int& carg, const _Ty& arg1, const _Args&...args)
{
    jsx_unpack_arg(ss, carg, arg1);
    jsx_unpack_arg(ss, carg, args...);
}

template<typename..._Args> inline
void jsx_vcall(const char*  func, const _Args&...args)
{
    std::stringstream sstreamArgs;
    sstreamArgs.precision(16);
    
    sstreamArgs << func << "(";

    int carg = 0;
    jsx_unpack_arg(sstreamArgs, carg, args...);

    auto actrualArgs = sstreamArgs.str();

    if (carg != 0)
        actrualArgs.pop_back(); // pop last ','   

    actrualArgs.append(");");

    jsval v1;
    bool succeed = ScriptingCore::getInstance()->evalString(actrualArgs.c_str(), &v1);
    assert(succeed);
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

C++调用JS,可变参模板实现,方便调用

标签:c++   js   crossplatform   

原文地址:http://blog.csdn.net/xseekerj/article/details/46768103

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!