如何将现有的序言文件查阅到 C++ 及其模块中?

How to consult existing prolog file into C++ and it's module?

大家好,我有一个简单的序言文件,可以计算阶乘,我想知道如何查阅 factorial.pl 文件并通过 C++ 调用它的命名事实的模块。

这是我的示例代码,但它不能正常工作。

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <SWI-Prolog.h>
#include <SWI-Stream.h>
#include <SWI-cpp.h>

int main(int argc, char **argv)
{
    PL_initialise(argc, argv);

    predicate_t p_consult = PL_predicate("consult", 1, "database");
    term_t t = PL_new_term_refs(3);
    PL_put_string_chars(t, "D:\factorial.pl");
    PL_put_integer(t + 1, 5);
    PL_put_variable(t + 2);
    qid_t query = PL_open_query(NULL, PL_Q_NORMAL, p_consult, t);
    int result = PL_next_solution(query);

    if (result)
    {
        int x;
        PL_get_integer(t + 2, &x);
        cout << "Found solution " << x << endl;
    }

    PL_close_query(query);

    cin.ignore();
    return 0;
}

和factorial.pl

fact(N, F) :- N =< 1, F is 1.
fact(N, F) :- N > 1, fact(N - 1, F1), F is F1 * N.

我找到了解决方案我把答案放在这里也许其他人也有同样的问题。

我猜想我的错误是在咨询中,我使用 PlCall 而不是 predicate 来咨询 pl 源文件,顺便说一下,你应该把 pl 源文件放在 cpp 文件所在的同一文件夹中。

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <SWI-Prolog.h>
#include <SWI-Stream.h>
#include <SWI-cpp.h>

int main(int argc, char **argv)
{
    int n;
    cout << "Please enter a number: ";
    cin >> n;

    PL_initialise(argc, argv);

    PlCall("consult('factorial.pl')");

    term_t a, b, ans;
    functor_t func;

    a = PL_new_term_ref();
    PL_put_integer(a, n);
    b = PL_new_term_ref();
    ans = PL_new_term_ref();
    func = PL_new_functor(PL_new_atom("fact"), 2);
    PL_cons_functor(ans, func, a, b);

    int fact;

    if (PL_call(ans, NULL))
    {
        PL_get_integer(b, &fact);
        cout << "Result is: " << fact << endl;
    }

    cin.ignore(2);
    return 0;
}