2.5 Examples (version 2)
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
    • Packages
      • A C++ interface to SWI-Prolog
        • A C++ interface to SWI-Prolog (Version 2)
          • Examples (version 2)
            • Hello(World) (version 2)
            • Adding numbers (version 2)
            • Average of solutions (version 2)

2.5.1 Hello(World) (version 2)

This simple example shows the basic definition of the predicate hello/1 and how a Prolog argument is converted to C-data:

PREDICATE(hello, 1)
{ cout << "Hello " << A1.as_string() << endl;

  return true;
}

The arguments to PREDICATE() are the name and arity of the predicate. The macros A<n> provide access to the predicate arguments by position and are of the type PlTerm. The C or C++ string for a PlTerm can be extracted using as_string(), or as_wstring() methods;11The C-string values can be extracted from std::string by using c_str(), but you must be careful to not return a pointer to a local/stack value. and similar access methods provide an easy type-conversion for most Prolog data-types, using the output of write/1 otherwise:

?- hello(world).
Hello world

Yes
?- hello(X)
Hello _G170

X = _G170