Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

怎么读取文本文件,调用对应的C++函数?

我有一些文本test.g,其内容:

a=fun_1(12, "hello")

该本文其实是想调用C++函数,获得返回值。比如上述,fun_1,其实是个C++函数:

string fun_1(int a, string b)

如果,fun_1(12, "hello")的结果是“This is from cpp fun”,那么,我程序读取文本文件,分析后应该得到a="This is from cpp fun",也就是为变量a赋值。

假如,我们已经分析好了,str1 = "fun_1", int a=12, str2="hello",我们可以使用str1,a,str2这三个变量,那么,我们怎么用这三个变量进行函数调用:fun_1(12, "hello")呢?

注意,用户可以自已自行决定这个函数名,也就说,无论什么函数名,C++程序中都要提供一个同名的C++函数供使用。

另外,用户可能有很多这样的函数,比如从fun_1到fun_100。

一种方法是:用一个map<string, void *> ,key存字符串“fun_1”, value存函数指针;为每一个可能被调用的C++函数添加一项到这个map里去。然后实际调用时,检查,如果检测到函数名在该map的key中,则调用相应的value。

有更好的办法?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你猜lua python v8这些是怎么做c/c++ binding的?
大兄弟 一个只能以字面量为参数调用方法的DSL有啥用啊
整天琢磨这些野路子不如去学习一下优秀的开源代码
对于你的问题 任何一个embedded script都有完整的解决方案

素质极差 我是吃饱了撑的跟你搭话

#include <iostream>
#include <stack>
#include <map>

#define VALUE_STRING 0
#define VALUE_INT 1

struct Value
{
    int type;
    union {
        int intValue;
        const char *strintValue;
    };
};

class Context
{
public:
    void pushInt(int num)
    {
        Value value = {VALUE_INT, num};
        this->stack_.push(value);
    }

    void pushString(const char *str)
    {
        Value value = {VALUE_STRING};
        value.strintValue = str;
        stack_.push(value);
    }

    int toInt()
    {
        Value val = stack_.top();
        stack_.pop();
        return val.intValue;
    }

    const char *toString()
    {
        Value val = stack_.top();
        stack_.pop();
        return val.strintValue;
    }

private:
    std::stack<Value> stack_;
};

typedef int (*pLocalFn)(Context *context);

std::map<const char *, pLocalFn> fnTable;

int fun_1(Context *p)
{
    int num = p->toInt();
    const char *str = p->toString();
    char *newstr = new char[strlen(str) + 20];
    sprintf(newstr, "%s%d", str, num);
    p->pushString(newstr);
    return 0;
}

int main()
{
    fnTable["fun_1"] = fun_1;

    Context *p = new Context();
    p->pushString("hello");
    p->pushInt(12);
    fnTable["fun_1"](p);

    const char *ret = p->toString();
    printf(ret);
    delete[] ret;
}

截屏2020-06-14 下午12.09.33.png

这代码能满足你的需求吗?

听不得不同意见你可以自己在家玩,
2020年了还在搞这种土味gui,
你知道Flutter是所有DirectUI的终极形态吗


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...