0

I'm calling C++ from Idris. It's working fine, mostly, but while I can use short strings fine, long strings get mangled. Here's my code

// C++
extern "C" {
    const char* foo() {
        std::string res = "foo";
        return res.c_str();
    }
}

and

-- idris
%foreign "C:foo,libfoo"
export
foo : String

main : IO ()
main = printLn foo

"foo" prints fine, but "fooooooooooooooo" prints "\65533\65533\65533\SOH".

joel
  • 6,359
  • 2
  • 30
  • 55
  • 2
    `return res.c_str();` returns a pointer to a temporary that no long exists once the function returns. This is Undefined Behaviour. – Richard Critten Dec 08 '21 at 13:48
  • Does this answer your question? [What is a dangling pointer?](https://stackoverflow.com/questions/17997228/what-is-a-dangling-pointer) – Richard Critten Dec 08 '21 at 13:49
  • This should be helpful too: https://idris2.readthedocs.io/en/latest/ffi/ffi.html#structs – Marek R Dec 08 '21 at 14:00
  • @MarekR i'm curious why you suggest structs. I've got it working with `strdup` so I can stick with C-strings rather than adding C++ `string` into the FFI – joel Dec 08 '21 at 14:04
  • This documents how memory should be managed. Procedure should be same for `struct` allocated on heap as for `char[]` allocated on heap. You have two choices, allocate on heap or change API in such way allocation is not needed. – Marek R Dec 08 '21 at 14:06
  • @MarekR ok thanks – joel Dec 08 '21 at 14:14

0 Answers0