🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Registering a std::function

Started by
3 comments, last by WitchLord 9 years, 11 months ago

Hello,

Complete AngelScript newbie here. I'm in need of emulating a global function with a std::function. I noticed a brief mention of this in the docs, but couldn't find any example.

Here's what I tried:


function<void(S1)> printFun = [] (S1 s) { print(s);} ;
engine->RegisterGlobalFunction("void print(S1)", asFUNCTION(printFun), asCALL_THISCALL_ASGLOBAL);

And the error was:


(0,0) : ERROR: Failed in call to function 'RegisterGlobalFunction' with 'void print(S1)' (Code: -24)

Advertisement

Ok, got it.


engine->RegisterGlobalFunction("void print(S1)", asMETHOD(decltype(printFun), operator()), asCALL_THISCALL_ASGLOBAL, &printFun)

EDIT: it would be useful if one could register the std::function by passing it by value, not by pointer. Right now the function needs to be declared in the same scope as the engine, which kind of defeats the purpose of lambdas.

I'm glad you figured out how to do it by yourself. I'll see if I can add an example in the documentation for future references.

I will not be able to use std::function as part of the core interface. One of the goals with the library to be as portable as possible, and this means that I cannot rely on C++11 features (since older compilers would then be excluded). Internally I don't even use any STL containers for the very same reason.

However, it should be quite easy for you to write a simple wrapper for RegisterGlobalFunction that could take a std::function by value and then transform it into the function and object pointer pair that the asIScriptEngine::RegisterGlobalFunction method expects.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

I'm not sure how I could do that. These functions would need to be stored somewhere during the life of the engine.

If you don't want to implement this storage yourself, you could store the pointer to std::function object as user data in the asIScriptFunction. The engine's function user data cleanup callback can then be used to destroy the std::function instance when the engine is released.

Regards,

Andreas

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement