I have exported functions with quite a bit of boilerplate, and am attempting to use string mixins to help hide the mess and sugar it up. The problem is that I have no idea how I could pass an anonymous function into the string mixin. I'd like to avoid writing the function as a string if at all possible.
// The function that the anonymous function below ultimately gets passed to.
char* magic(F...)(string function(F) func) { ... }
string genDcode(string name, alias func)() {
return xformat(q{
extern(C) export char* %s(int blah) {
// What would I inject into the string in place of 'func'
// in order to call the 'func' passed into the template?
return magic(func);
}
}, name);
}
// Calls a function to generate code to mix into the global scope.
// The anonymous function must allow abritrary parameters.
mixin(genDcode!("funcName", function(string foo, float bar) {
return "Herpderp";
}));
This is of course not the full picture, and most of the boilerplate is trimmed, but it's enough to show the problem. I've thought about injecting the function pointer as an int, and casting back into a callable type, but unsurprisingly, you can only get the function pointer at runtime.
I've tried mixin templates, which elimitates the function passing problem, but the linker cannot seem to find export functions generated from such mixins. They appear to have some extra qualifiers, and I can't use a dot in the DEF file.
Old question, but a relatively new feature might help solve it: D now has a pragma(mangle) which you can put inside a mixin template to force a particular name for the linker:
mixin template genDcode(string name, alias func) {
// pragma mangle is seen by the linker instead of the name...
pragma(mangle, name) extern(C) export char* impl(int blah) {
return magic(func);
}
}
char* magic(F...)(string function(F) func) { return null; }
mixin genDcode!("funcName", function(string foo, float bar) {
return "Herpderp";
});
Related
I have a legacy C code base, which I am migrating to C++ in a piecemeal fashion. It includes an interpreter, so there is a need to wrap static functions and arguments for use by the interpreter. So a typical function for export to the interpreter may have the following signature:
static void do_strstr(struct value * p)
and be exposed to the interpreter like so:
using vptr = void (*) ();
template <typename Func>
constexpr vptr to_vptr(Func && func)
{ return reinterpret_cast<vptr>(func); }
struct function string_funs[] = {
...
{ C_FN3, X_A3, "SSI", to_vptr(do_strstr), "find" },
...
};
This has been proven to work. The drawback with the method so far is that the called function must allocate memory onto a temporary stack. An improvement would be where the called function just returns a string, for example. This function is then wrapped, where the wrapper does the memory magic behind the scenes. This allows functions to created in a more vanilla way.
Here is an implementation which concatenates two strings using my improved method:
static std::string do_concata(struct value* p)
{
std::string s1 = (p)->gString();
std::string s2 = (p+1)->gString();
return s1+s2;
}
I create a helper function:
static void do_concata_1(struct value* p)
{
wrapfunc(do_concata)(p);
}
where the somewhat generic wrapper is defined as:
std::function<void(struct value*)>
wrapfunc(std::function<std::string(struct value*)> func)
{
auto fn = [=](struct value* p) {
std::string s = func(p);
char* ret = alloc_tmp_mem(s.size()+1);
strcpy(ret, s.c_str());
p->sString(ret);
return;
};
return fn;
}
which is exposed to the interpreter as follows:
struct function string_funs[] = {
...
{ C_FN2, X_A2, "SS", to_vptr(do_concata_1), "concata" },
...
};
I am not satisfied with this solution, though, as it requires a helper function for each function I define. It would be better if I could eliminate do_concata_1 and write another function that wraps the wrapfunc.
And this is where the problem is. If I write:
vptr to_vptr_1(std::function<void(struct value*)> func)
{
return to_vptr(wrapfunc(func));
}
then the compiler complains:
stringo.cc: In function ‘void (* to_vptr_1(std::function<void(value*)>))()’:
stringo.cc:373:30: error: could not convert ‘func’ from ‘std::function<void(value*)>’ to ‘std::function<std::__cxx11::basic_string<char>(value*)>’
return to_vptr(wrapfunc(func));
which is bizarre in my mind, because where did the std::__cxx11::basic_string<char> come from? It should be void, surely?
I'm at a loss to see what the fix should be. I am also a bit confused as to whether I should be passing copies of functions, references to functions, or the enigmatic && r-vale references.
In to_vptr_1(), func is established as a function that returns void. But func is passed to wrapfunc(), which expects a function that returns std::string. The compiler does not have a way to convert func from std::function<void(struct value*)> to std::function<std::string(struct value*)>, so it emits the error message.
reinterpret_cast from std::function to raw function pointer is not going to work. This question has some good discussion on the topic, and this one has a solution that could perhaps be reworked for this situation.
Consider the pair of functions below:
double MYAPI foo(double x) {
return x;
}
Register register_foo_([] {
return reg(&foo, "foo", ...); // function name repeated used
});
register_foo_ is a global variable, initialized before dllmain, whose constructor takes a lambda that repeatedly references the name of the function above it literally. It would be great if the registration code can move inside the function above to reduce the chance of making an error. I tried:
double MYAPI foo(double x) {
static Register register_foo_([] {
return reg(&foo, "foo", ...); // static local does not initialize before dllmain
});
return x;
}
If the above code works, then I can easily turn it into a macro that makes use of __FUNCNAME__. Is there a way to force the initialization of static local variable register_foo_ before dllmain?
Static variables local to a function (method) are initialized on first use of the function they're in. (They're zero-initialized at program load, then initialized "properly" via code when the function is first entered.) See the answers to this question. So your proposed movement of that code into the function changes the semantics of initialization, and it won't work.
Your original code worked, so what you apparently wanted was to move the code inside the function so it was somehow tied closer together in your mind - or the mind of a reader of the code - so that you could see that your string constant name and function name were right. Also maybe so that you could ensure the registration was done. And therefore what you want is to accomplish DRY.
The traditional (and only) way to accomplish that is by using a preprocessor macro that expands into the registration call and the function header.
You proposed using a macro yourself - now expand the macro so it not only generates the registration function but also the function header.
I suppose you want to achieve a syntax similar to:
DEFINE_FUNC(void, foo, (double x)) {
return x;
}
... and have the boilerplate autogenerated. That's actually very simple to do if you bring the Register above the function, with the help of a declaration:
#define DEFINE_FUNC(Ret, name, args) \
Ret name args; \
Register register_##name##_([] { \
return reg(&name, #name, ...); \
}); \
Ret name args
No, there's not. That's your answer.
This question already has answers here:
What would be a proper invalid value for a pointer?
(7 answers)
Closed 7 years ago.
I'd like to have a function with an optional parameter but without overloading the function. The reason I don't want to overload is because the function body is quite long, and the version with the optional parameter just differs by a single line.
void myFunction(MyClass my_optional_arg = MyClass())
{
// lots of statements
if (optional_argument_was_passed)
doSomething(my_optional_arg);
// lots more statements
}
int main()
{
myFunction();
MyClass my_optional_object();
myFunction(my_optional_object);
}
The problem that I have with the default parameter route is that I don't know how to check whether the optional parameter was passed or not, i.e., I don't know how to set the boolean flag optional_argument_was_passed. For example, just testing equality of the parameter with the default isn't sufficient because that same default value could be passed into the function. What I'd really like is something like this:
void myFunction(MyClass my_optional_arg = some_unique_null_value)
{
// lots of statements
if (my_optional_arg != some_unique_null_value)
doSomething(my_optional_arg);
// lots more statements
}
It has been suggested that I do something like this:
void myFunction()
{
MyClass my_object();
myFunction(my_object);
}
However, this is not quite what I need; the myFunction(MyClass) function is not necessarily the ultimate function to be used. If I call the function without the optional argument, myFunction(), then I don't want any object of class MyClass to even enter the function at all; rather, the statement that uses this object, called doSomething(MyClass) above, should be omitted.
It has also been suggested that I remove the common parts of both functions to its own function myFunction() and then create an overloaded wrapper function to call the statements with the optional parameter:
void myFunction(MyClass my_optional_arg)
{
doSomething(my_optional_arg);
myFunction();
}
This is a solution, but it would be a bit messy because I have a lot of statements before AND after the doSomething(MyClass) call, so I'd need to split the function into several parts:
void myFunction(MyClass my_optional_arg)
{
myFunctionPartA();
doSomething(my_optional_arg);
myFunctionPartB();
}
void myFunctionPartA()
{
// lots of statements
}
void myFunctionPartB()
{
// lots more statements
}
if the functions are similar then call one from the other. OR have an internal 'do all the work and take all the paramters' function that all the overloads call. This is a very common tactic
void Func() // func with foo defaulting to 42
{
Func(42);
}
void Func(int foo)
{
// one million lines of code
}
Say that you define a callback function as such:
typedef std::function<void(float)> Callback;
And you have a function as such:
void ImAFunction(float a)
{
//Do something with a
}
Is there a way to be able to store a function without an argument then pass one to it at a later time?
Such as this:
//Define the Callback storage
Callback storage;
storage = std::bind(ImAFunction, this);
//Do some things
storage(5);
This wont work which I explain with some of my real code below.
I can get close to what I wan't if I bind the value in with the std::bind function. Such as:
//Change
//storage = std::bind(ImAFunction, this);
storage = std::bind(ImAFunction, this, 5.0); //5.0 is a float passed
This works but when I go to pass a value through the function the outcome is whatever I set it to before:
storage(100); //Output is still 5
I am basing the fact that I think this is possible on this article.
http://www.cprogramming.com/tutorial/function-pointers.html
It doesn't use the function or bind functions but it does pass pointer arguments and performs exactly what I need. The reason I don't just skip the bind function is because I am trying to store the function in a class (private) and I can't store it if it's a template because it's created with the class.
The error produced above comes from this code:
struct BindInfo {
Callback keyCallback;
int bindType;
bool isDown;
bool held;
std::string name;
};
template <class T1>
void bindEvent(int bindType, T1* keydownObj, void(T1::*keydownF)(float), std::string name)
{
BindInfo newKeyInfo = { std::bind(keydownF, keydownObj), bindType, false, false, name };
inputBindings.insert(std::pair<int, BindInfo>(BIND_NULL, newKeyInfo));
};
The error is:
No viable conversion from '__bind<void(Main::*&)(float), Main *&>' to 'Callback' (aka 'function<void (float)>'
Is this possible? Thanks in advance.
You can include a placeholder for an unbound argument:
std::bind(&Main::ImAFunction, this, std::placeholders::_1);
If you find that a bit of a mouthful, a lambda might be more readable:
[this](float a){ImAFunction(a);}
It sounds like what you're looking for is a function pointer. While I don't have a lot of experience using them in C++ I have used them in C so: Yes, it is possible. Perhaps something like this:
void (*IAmAFunctionPointer)(float) = &IAmAFunction;
The best way to think about that line is, that IAmAFunctionPointer is a pointer (hence the *), it returns a void, and takes a float. Then later:
float a = 5;
IAmAFunctionPointer(a);
You could even design it so that the callback function is passed into the method (I assume this is what you're looking for).
void DoStuffThenCallback(float a, void (*callback)(float))
{
//DoStuff
callback(a);
}
further reading: http://www.cprogramming.com/tutorial/function-pointers.html
Somewhat related to my previous question here
Is there a way to get the calling Object from within a function or method in d?
example:
class Foo
{
public void bar()
{
auto ci = whoCalledMe();
// ci should be something that points me to baz.qux, _if_ baz.qux made the call
}
}
class Baz
{
void qux()
{
auto foo = new Foo();
foo.bar();
}
}
Questions:
Does something like whoCalledMe exist? and if so, what is it called?
if something does exist, can it be used at compile time (in a template) and if so, how?
Alternatively;
is it possible to get access to the call stack at runtime? like with php's debug_backtrace?
To expand on what CyberShadow said, since you can get the fully qualified name of the function by using __FUNCTION__, you can also get the function as a symbol using a mixin:
import std.stdio;
import std.typetuple;
void callee(string file=__FILE__, int line=__LINE__, string func=__FUNCTION__)()
{
alias callerFunc = TypeTuple!(mixin(func))[0];
static assert(&caller == &callerFunc);
callerFunc(); // will eventually overflow the stack
}
void caller()
{
callee();
}
void main()
{
caller();
}
The stack will overflow here since these two functions end up calling each other recursively indefinitely.
It's not directly possible to get information about your "caller". You might have some luck getting the address from the call stack, but this is a low-level operation and depends on things such as whether your program was compiled with stack frames. After you have the address, you could in theory convert it to a function name and line number, provided debugging symbols are available for your program's binary, but (again) this is highly platform-specific and depends on the toolchain used to compile your program.
As an alternative, you might find this helpful:
void callee(string file=__FILE__, int line=__LINE__, string func=__FUNCTION__)()
{
writefln("I was called by %s, which is in %s at line %d!", func, file, line);
}
void caller()
{
// Thanks to IFTI, we can call the function as usual.
callee();
}
But note that you can't use this trick for non-final class methods, because every call to the function will generate a new template instance (and the compiler needs to know the address of all virtual methods of a class beforehand).
Finding the caller is something debuggers do and generally requires having built the program with symbolic debug information switches turned on. Reading the debug info to figure this out is highly system dependent and is pretty advanced.
The exception unwinding mechanism also finds the caller, but those tables are not generated for functions that don't need them, and the tables do not include the name of the function.