为什么我不能在“Prolog + C”中存储一个变量的地址?

时间:2014-04-12 18:26:00

标签: c prolog ffi gnu-prolog

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

的Prolog:

:-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

我错了吗?有人能给我一些帮助吗?

2 个答案:

答案 0 :(得分: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  */
 ...
}

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

答案 1 :(得分:1)

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

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

编辑:你可能只需要将它从一个int改为long,或者加倍......就像那样。