Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

foreign predicate, how to return a string

1 view
Skip to first unread message

lucie

unread,
Oct 1, 2009, 2:09:04 PM10/1/09
to
Hi,

Using Gprolog, I'd like to create a string in a foreign predicate,
then return it.
Here is some code that fails to do that:

% cat ex01.pl
:- foreign(fgn(+string, +positive, +positive, -positive, -positive,-
string)).
go:- I='input string',A=10,B=20, fgn(I,A,B,X,Y,Z),write('strlen
('),write(I),write(')= '),write(X),nl,
write('product: '), write(A),write('*'),write(B),write('='), write
(Y),nl,write(Z),nl.
:-initialization(go).

% cat ex01.c
#include <string.h>
#include "gprolog.h"

Bool fgn(char *str, long* w, long* h, long * res1, long * res2, char *
res3)
{
*res1= strlen(str);
*res2= (long)w * (long)h;
strcpy(res3,"Hello from C!");
return TRUE;
}

% cat Makefile
ex01: ex01.pl ex01.c
gplc --no-top-level ex01.pl ex01.c
./ex01

%make
gplc --no-top-level ex01.pl ex01.c
./ex01
Fatal Error: Segmentation Violation


I think there may be an mallocation problem with res3, but I can't
solve it. Thanks if you can help me.

cvalou

unread,
Oct 8, 2009, 4:02:25 AM10/8/09
to
There are several mistakes in your examples. When an argument is
prefixed with - in a foreign declaration then the C received type is a
pointer to the basic type. Here is a fix:

%ex01.pl


:- foreign(fgn(+string, +positive, +positive, -positive, -positive, -
string)).

go:-
I='input string',
A=10,
B=20,
fgn(I,A,B,X,Y,Z),
write('strlen('), write(I), write(')= '), write(X), nl,
write('product: '), write(A), write('*'), write(B), write('='),
write(Y), nl,
write(Z), nl.

:-initialization(go).


%ex01.c

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

Bool fgn(char *str, long w, long h, long *res1, long *res2, char
**res3)
{
*res1= strlen(str);
*res2= w * h;
*res3 = "Hello from C!";
return TRUE;

0 new messages