Res: [mercury-users] Passing structures from and to C

Paul Bone pbone at csse.unimelb.edu.au
Wed Jul 11 09:24:16 AEST 2007


On 11/07/2007, at 5:58 AM, Alexsandro Soares wrote:

> Thanks by the answers.
>
> For others beginner Mercury programmers, such as myself, I put here  
> my final code:

Thanks.

This raises a question for me though about modes.  See below.

> ----------------------------   struct.m   ----------------------------
>
> :- module struct.
>
> :- interface.
> :- import_module io.
>
> :- type person.
> :- pred main(io::di, io::uo) is det.
>
> :- implementation.
> :- import_module char, list, int, float, string.
>
> :- pragma foreign_type("C", person, "person * ").
>
> :- pragma foreign_decl("C", "#include <string.h>").
> :- pragma foreign_decl("C", "
>      typedef struct {int age; MR_String name;} person;
>
>      extern person * crPr(int, char *);
>      extern void freePr(person *);
> ").
>
> :- pragma foreign_code("C","
> person * crPr(int a, char * name)
> { person * p;
>   p = (person *) malloc (sizeof(person));
>
>   p->age  = a;
>   p->name = (MR_String) strdup(name);
>
>   return p;
> }
>
> void freePr(person * p)
> {
>     free(p->name);
>     free(p);
> }
> ").
>
> :- pred createStruct(int::in, string::in, person::out) is det.
> :- pred freeStruct(person :: in, io::di, io::uo) is det.
>
> :- pragma foreign_proc("C", createStruct(A::in, Name::in, P::out),
>      [will_not_call_mercury, thread_safe, promise_pure],"
>      P = crPr(A, Name);
> ").

Since crPr uses malloc to create a person it must be freed later, and  
must not be freed twice or used after it has been freed.  Is a mode  
such as uo better here?

Each time this is called it will create a different person (at a  
different memory location), for mercury's purposes is that still pure?


>
> :- pragma foreign_proc("C", freeStruct(P::in, IO0::di, IO::uo),
>      [will_not_call_mercury, thread_safe, promise_pure],"
>      freePr(P);
>      IO=IO0;
> ").

Similarly should the input person here be di, since we must not use  
it after freeing it?



--------------------------------------------------------------------------
mercury-users mailing list
Post messages to:       mercury-users at csse.unimelb.edu.au
Administrative Queries: owner-mercury-users at csse.unimelb.edu.au
Subscriptions:          mercury-users-request at csse.unimelb.edu.au
--------------------------------------------------------------------------



More information about the users mailing list