Search code examples
chaiscript

Recommendations for returning const char * as a string value using chaiscript?


Running into a very odd challenge with Chaiscript today, I'm sure it's lack of understanding but I haven't been able to resolve it yet. Hoped lefticus or others could shed some light on it.

When my C++ class returns a "const char *" calling that method results in the first character of the string only.

"teststring" would return "t", etc.

class Item{
     const char *getName();
};
chai.add(chaiscript::fun(&Item::getName), "getName");

...

chai.eval("var i = Item(); print(i.getName());");

...

"t"

Is there a way to tell ChaiScript the return type of my method better so that it will treat it like a char *? Perhaps that's just not supported and I need to re-write those methods to use std::strings.. Any recommendations would be great.

Thanks!


Solution

  • There's no way for ChaiScript to (safely) know the difference between a pointer to an individual char or a pointer to a string of null terminated char. Both are valid possibilities, which is why the C++ Core Guidelines say that a * should denote a single, optional item only.

    Your best bet when working with ChaiScript, if you want ChaiScript to be able to use the result value internally, is just to return a std::string or const std::string &.