Question

So basically I want to call some C code from Prolog, and here is the code:

Prolog:

:-foreign(ptraddr_wrapper(+integer,-integer)).
:-foreign(ptrlval_wrapper(+integer,-integer)).
:-foreign(ptre_wrapper(+integer,-integer)).


% p = &b;
babelTPtr(Var, Val) :- ptraddr_wrapper(Val, Var).
% a = *p;
babelEPtr(Var, Val) :- ptre_wrapper(Val, Var).
% *p = 2;
babelLValPtr(Var, Val) :- ptrlval_wrapper(Val,Var).
% a = b;
babelAssign(Var, Val) :- Var is Val.

main :-
babelAssign(A, 1),
babelAssign(B, 2),
babelTPtr(P, A),
babelLValPtr(P, 2),
%% babelEPtr(B, P),

% print out

write(A), nl.

C:

#include </usr/local/gprolog-1.4.4/include/gprolog.h>
#include <string.h>


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

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

PlBool ptre_wrapper(int* ptr, int* res){
   *res = *ptr;
if(res==NULL){
 return PL_FALSE;
}else{
   return PL_TRUE;
   }
}

The problem is that, after I run this code, the output is :

  0xbfae8bcc       <-- it is on the stack, right
  0xbfae8bcc       <-- it is on the stack, right
   1              
  0x82abec4        <-- Why?
    2
    2

I don't understand why the fourth output is a new memory address, to my understanding, it should also be 0xbfae8bcc,

am I wrong? Could anyone give me some help?

Was it helpful?

Solution

What you try to do is simply impossible (it would be very dangerous). In the C part, the res pointer is the address of a temporary variable which, at the return of the function, should contain a result. This result is unified with the corresponding Prolog argument bu the foreign interface. You can look at the global variables facilities offered by gprolog, in particular g_link/2. see doc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top