Advertisement

String to const char conversion

Started by January 08, 2025 09:31 AM
4 comments, last by Juliean 2 weeks, 1 day 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.

void test()
{
	print("String1"); //  Passing in a pointer to an address of a string (address of 'S')
    print("String1" + "String2"); // Adding two memory addresses together const char has no '+' operator
	print("String1" + "String2" + "String3"); // Not sure.
}


// This is how you generate a unique const char.
const char* StringToConstChar(string& str)
{
	char* newChar = new char[str.size()+1];//Might need a +1 for the NULL '\n'
    const char* strToChar = str.c_str();
    memcpy(newChar, strToChar, str.size()+1);
    return newChar;
}

NBA2K, Madden, Maneater, Killing Floor, Sims

@dpadam450 You probably missed that this is a topic about AngleScript, and the first piece of code you quoted is AngelScript-code, not C++, so your comments there do not apply.

Advertisement