c++ - 在C程序中集成Prolog

标签 c++ c prolog ffi swi-prolog

我想用C++编写一个主程序,该程序将动态生成事实来建立知识库,然后该程序可以调用某些.pl中定义的规则 文件并获取结果。例如, main.c

int main()
{
   //generate facts like 
    // blue(car), red(bike), etc
    // do queries
    PL_call( "consult( 'pred.pl' )" );
    ...
    PL_call(goal_term, NULL);
}

pred.pl

whatisblue(X) :- blue(X).
whatisred(X) :- red(X).

我该怎么做?

我阅读了 C 接口(interface)上的 swi-prolog 手册,但只看到如何在 Prolog 中调用 C 模块或在 C 中调用 Prolog,我没有看到如何混合在 C 和 Prolog 中定义的谓词。是否可以?谢谢。

最佳答案

我现在不可能给出详细的答案,但总的来说,你的问题的答案是"is"。

只是,在C++中,使用C++接口(interface)。它比 C 简单得多。所以使用 PlCall、PlTermv 等...

问题是在 PlCall(s) 之前和之后正确绑定(bind)变量,以便您可以与 Prolog 交换值。

例如,为了简化结构化值的构建,请查看 these macros注释,谓词0,谓词1,...和结构1,结构2,...,或考虑

#define unary(X) PlTerm X; PlCompound X ## _t(#X, X);

允许输入 code

attrs2format_t::const_iterator p = attrs2format.find(k);
if (p == attrs2format.end()) {
    // attributes documented here:
    // http://www.swi-prolog.org/pldoc/doc_for?object=prolog_colour:syntax_colour/2

    unary(colour)
    unary(background)
    unary(bold)
    unary(underline)

    // use unification to match list' elements
    PlTail attrs(attr_list);
    PlTerm attr;
...

您可以找到here关于 SWI-Prolog 接口(interface)的一些一般注意事项

关于c++ - 在C程序中集成Prolog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054166/

相关文章:

c++ - 如何 SFINAE 启用返回 `auto` 的成员函数

c++ - 为什么 pthread_cond_timedwait 文档谈论 "unavoidable race"?

Python struct.unpack 从 4 字节到 char

Prolog、失败且不回溯

prolog - prolog 如何使用 succ 遍历递归查询?

c++ - 我可以为抛出 bad_cast 的情况安装自定义处理程序吗?

c++ - mt.exe : general error c101008d: Failed to write the updated manifest to the resource of file . .. 访问被拒绝

c - 升级服务器可执行文件而不丢失用户连接

c - Eclipse 项目不能包含 tchar.h

Prolog - 祖先谓词实现的 2 种方法