[m-users.] Segmentation violation on FFI wrapper for linenoise-ng

Julien Fischer jfischer at opturion.com
Sun Jun 20 00:11:24 AEST 2021

On Sat, 19 Jun 2021, Sean Charles (emacstheviking) wrote:

> :facepalm:
> I took that print line out, removed ’the fix’/…….I don’t think I need tell you how it went.
> Sometimes it never fails to baffle me, after 35 years, that sometimes you can fail to read and understand your own code.
> :D
> Sigh… you live and learn. I hope.
> Thanks Julien, I am going outside to self-flagellate with some nettles I mowed down this morning…..

For the record, I would probably wrap the linenoise() function as in the
following (untested) code:

     :- type ln_read_result
         --->  ok(string).
         ;     eof.

     :- pred ln_read(string::in, ln_read_result::out, io::di, io::uo) is det.

     ln_read(Prompt, Result, !IO) :-
         do_ln_read(Prompt, RawResult, Line, !IO),
             RawResult = ok,
             Result = ok(Line)
             RawResult = eof,
             Result = eof

      :- type raw_ln_result
         --->     ln_result_ok
         ;        ln_result_eof.

      :- pragma foreign_export_enum("C", ln_result/0, [uppercase]).

      :- pragma foreign_decl("C", "#include ""mercury_string.h""").

      :- pred do_ln_read(string::in, raw_ln_result::out, string::out, io::di, io::uo)
          is det.

      :- pragma foreign_proc( "C",
          do_ln_read(Prompt::in, Result::out, Line::out, _IO0::di, _IO::uo),
          [will_not_throw_exception, promise_pure, tabled_for_io],
          char* line = linenoise((const char*) Prompt);
          if (line) {
              Result = LN_RESULT_OK;
              // Copy the string on to the Mercury heap.
              MR_make_aligned_string_copy(Line, line);
          } else {
              Result = LN_RESULT_EOF;
              // Set Line to a valid value so we do not crash the
              // debugger.
              Line = MR_make_string_const("""");


More information about the users mailing list