Sign in to follow this  
Tylon

Binding functions that take std::string

Recommended Posts

Tylon    181
I have some c++ functions that I want to bind to angelscript, and I do not have access to their source (they are in a dll) only the header defining them. Some of the functions take std::strings as parameters, but of course angelscript's string class is the asCScriptString, which wraps an std::string. Since the std::string is aligned at the beginning of the asCScriptString class, I can actually bind these functions, and it appears to work, but is it safe? Can it lead to any memory leaks or such? basically I have a c function such as void sayhi(const std::string& hi) { printf(hi.c_str()); } and I can bind it like r = scr->RegisterGlobalFunction("void sayhi(const string& in)", asFUNCTION(sayhi), asCALL_CDECL); and It works fine, but I am worried, that since angelscript is actually passing it an asCScriptString, that there may be some leaks, or stack not being cleaned up properly? Of course the obvious way around it is for me to wrap all the functions and classes to take a asCScriptString, but I would rather not do that if i can just bind them directly?

Share this post


Link to post
Share on other sites
WitchLord    4677
As long as the function takes a reference to a std::string you will not have any problems passing a reference to a asCScriptString (I designed asCScriptString with this in mind). In this case it is the caller, not the callee that cleans up the object. The callee only receives a pointer to the object.

If the function takes a std::string by value then you will be forced to write a wrapper, since then asCScriptString wouldn't be compatible.

Share this post


Link to post
Share on other sites
Tylon    181
I see, thanks.

Similarly, if it the c++ function takes a const char* or char* do I need to write a wrapper? The above method obviously doesnt work on those cases, but is there any kinda hack that would allow a string to be recognised as a const char* or char*?

Share this post


Link to post
Share on other sites
WitchLord    4677
In this case you are unfortunately forced to write a wrapper. Unless you'd prefer to register a second string type in AngelScript and have the script writer explicitly convert the asCScriptString to the char* type that you registered.

In my opinion, the wrapper is the best way to go.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this