1

所以基本上我想从 Prolog 调用一些 C 代码,这里是代码:

序言:

:-foreign(fun1(+integer,-integer)).
:-foreign(fun2(+integer,-integer)). 

% p = b;
testfuna(Var, Val) :- fun1(Val, Var).
% p = &b;
testfunb(Var, Val) :- fun2(Val, Var).

main :-
A is 1,
testfuna(A, P),
write(P),
testfunb(A, P),
write(P),

% print out

write(A), nl.

C:

#include <gprolog.h>
#include <string.h>

PlBool fun1(int ptr, int* res){
    *res = ptr;
    printf("%d\n", *res);
    if(res==NULL){
      return PL_FALSE;
    }else{
      return PL_TRUE;
    }
}

PlBool fun2(int val, int* res){
   *res = &val;
   printf("%p\n", *res);
   if(res==NULL){
      return PL_FALSE;
   }else{
      return PL_TRUE;
   }
}

我用它编译成二进制格式:

gplc -o sample sample.c sample.pl

问题是,在我运行这段代码之后,输出是:

  1    <--- right
  1    <--- match, right!
  0xbff2160c       <-- it is on the stack
  -911860     <--- why?              

我不明白为什么第四个输出是一个新的内存地址,据我了解,它也应该是0xbff2160c

我错了吗?谁能给我一些帮助?

4

2 回答 2

1

只是一个猜测,但它是传递给 prolog 的整数大小的限制吗?

我不知道 gnu prolog,但是在 swi prolog 中有一个特殊的调用 PL_get_pointer 和 PL_put_pointer 专门用于处理地址.. PL_get_integer 和 PL_put_integer 不起作用。看看gnu中的等价物..地址可能被破坏了。

编辑:您可能只需要将它从 int 更改为 long 或 double .. 类似的东西。

于 2014-04-12T19:36:29.933 回答
1

它们是有区别的。在你的函数fun2中,你在堆栈上得到一个整数,&val是那个整数的地址。

PlBool fun1(int ptr, int* res){
 *res = ptr;  /* ptr is what you got from prolog */
 ...
}

PlBool fun2(int val, int* res){
 *res = &val; /* val is a copy on the stack here, */
 /* you don't use at all what you got from prolog, only the address */
 /* of a local copy in the stack  */
 ...
}

另外,(我不知道任何序言,所以我不确定你在那部分做了什么)如果你试图将指针传递为int,它将不起作用。通常,指针的大小和整数的大小可以不同。int用于存储 a是行不通pointer的,例如在 64 位 intel 上,通常int是 32 位整数,而指针是 64 位无符号整数,不适合 32 位。

于 2014-04-12T19:28:45.417 回答