How to pass any memory to a function through another function

廉价感情. 提交于 2020-01-25 08:22:06

问题


I'm making an event dispatch system where functions are registered to a handler which then calls them as it sees fit. The delegates are in an associative array of dynamic arrays which maps an integer "key" to a number of delegates. This setup is necessary so that the handler is extendable with other delegate function types.

class Handler {
    void addDelegate(void delegate(...) del, int event) nothrow @safe {
        _tick[event] ~= del;
    }

    void callEvent(int event, ...) {
        runDelegates(event, _argptr);
    }
private:
    void delegate(...)[][int] _delegates;

    void runDelegates(uint type, ...) {
        foreach (d; _tick[type]) {
            d(_argptr);
        }
    }
}

The issue arises where I want to pass an argument to these delegates. There is no safe or checkable "type" which allows any memory to be passed. Using typeless varargs and passing _argptr (the value used to access varargs) passes the literal value of the pointer as an argument.

The code that I am using right now invokes a situation like this:

void vararg2(...) {
    writefln("vararg2 _argptr: %s", _argptr);
}

void vararg1(...) {
    writefln("vararg1 _argptr: %s", _argptr);
    vararg2(_argptr);
}

int main() {
    vararg1("a");
}

run.dlang.io

If you run the example, the _argptr values are different, and therefore dereferencing will give a different result.

The only method I can think of to do this is to replace the varargs with a void* argument. Is there another way?

来源:https://stackoverflow.com/questions/58640856/how-to-pass-any-memory-to-a-function-through-another-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!