Advertisement

Binding functions that take std::string

Started by November 28, 2005 10:55 AM
2 comments, last by WitchLord 19 years ago
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?
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.

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

Advertisement
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*?
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.

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