Question

Basically I am trying to simulate C pointer dereference using gnu-prolog.

Here is the code:

Prolog

:-foreign(fun(+integer,-integer)).

% p = &b;
testfun(Var, Val) :- fun(Val, Var).

main :-
A is 1,
testfun(A, P),
write(P),

C:

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

PlBool fun(int ptr, int* res){
    *res = &ptr;                  // this is wrong
    if(res==NULL){
      return PL_FALSE;
    }else{
      return PL_TRUE;
    }
}

So basically it is wrong, because ptr is just a temp variable on the stack, and its memory will be deallocated after the calling fun.

So my question is, is it possible to get the variable's memory addresses in gnu prolog (For example, in this case, it is the address of A, not the address of ptr)?

Was it helpful?

Solution

Gnu Prolog is pretty easy to extend by writing C routines and linking them into an executable. but if you are trying to "simulate the memory reference relation", then I'm doubtful that hacking in an actual memory address function would be useful.

Instead, as @lurker suggests, you likely want to "simulate" a memory/computer architecture and then some C-like language that "executes" on that. It sounds a little ambitious, but the simulation of a CPU in Prolog has been asked about already, and more recently here asked about by you, with Answer by lurker.

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