Advertisement

String to const char conversion

Started by January 08, 2025 09:31 AM
2 comments, last by definer 2 days, 18 hours ago

I need to make a const char* system, but there're some problems.
I registering const char like this:

void ConstructConstCharString(string* thisPointer, const char* ptr)
{
    new(thisPointer) string(ptr);
}
const char* StringToConstChar(string& str)
{
    return str.c_str();
}

RegisterStdString(engine);
engine->RegisterObjectType("charptr", sizeof(const char*), asOBJ_VALUE | asOBJ_POD | asOBJ_APP_PRIMITIVE);
engine->RegisterObjectBehaviour("string", asBEHAVE_CONSTRUCT, "void f(charptr)", asFUNCTION(ConstructConstCharString), asCALL_CDECL_OBJFIRST);
engine->RegisterObjectMethod("string", "charptr opImplConv() const", asFUNCTION(StringToConstChar), asCALL_CDECL_OBJFIRST);
engine->RegisterObjectMethod("string", "charptr opConv() const", asFUNCTION(StringToConstChar), asCALL_CDECL_OBJFIRST);

After performing the conversion, the string is cleared for some reason and as a result, an empty string appears in the print (AngelScript):

void test()
{
	print("String1"); // Works
    	print("String1" + "String2"); // Print empty string
	print("String1" + "String2" + "String3"); // Works for some reason
}

print func:

void print(const char* str)
{
   std::cout << str << "\n";
}

How to fix this?

str.c_str() doesn't create a new memory buffer, it is just returning the address of the internal buffer to the std::string, so when the std::string instance is freed it will also free the internal buffer. The freeing of the internal buffer may or may not change the content of it, so it possible that the string value will remain for a while, but you shouldn't count on it as the memory may be overwritten at any time.

In order to solve this you will need to copy the memory of the std::string to a memory buffer that you can control the life time of.

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 will use a global vector to collect the strings and then clean them.

Advertisement