1.7 Examples
All Application Manual Name SummaryHelp

  • Documentation
    • Reference manual
    • Packages
      • A C++ interface to SWI-Prolog
        • A C++ interface to SWI-Prolog
          • Examples
            • Hello(World)
            • Adding numbers
            • Average of solutions - calling a Prolog goal

1.7.1 Hello(World)

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;25The 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, so this isn't recommende. 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