1

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!

OldSchool
  • 152
  • 9

1 Answers1

2

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 &.

lefticus
  • 3,346
  • 2
  • 24
  • 28
  • Yep, that's pretty much what I did. C++ Core Guidelines.. doh! – OldSchool Oct 10 '16 at 19:39
  • This is a good idea in principle, but it's not uncommon in C++ that we have to deal with const char* as a string type, potentially coming from code we have no control over, i.e. we cannot rewrite this to use std::string. I also think that it's usually implictit that a const char* is a null-terminated string - we can't know in C++ either if it's a single character based purely on type, but almost everywhere accepting a character pointer is working with C-style strings, including the std::string constructor. I think it's safe to assume that if we explicitly want to work with a const char*, – stellarpower Apr 07 '22 at 13:52
  • this is going to be a null-terminated. Is there a recommended way in ChaiScript that we can work around this explicitly? As a beginner with the kit, currently I am attempting to add a custom explicit function to perform this conversion. The fact that Chai is very thin in terms of bridging between the script and C++ backing is one of its main attractions. Most of the work in adding scripting to our projct has been explicitly exposing what we need to Chai, so, it can be a shame if we keep needing more and more glue code and boilerplates on the C++ side for pretty common situations like this. – stellarpower Apr 07 '22 at 13:56