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

Alexsandro Soares a_s_soares at yahoo.com.br
Wed Jul 11 05:58:39 AEST 2007


Thanks by the answers.

For others beginner Mercury programmers, such as myself, I put here my final code:

----------------------------   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);
").

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

:- func getName(person) = string.

:- pragma foreign_proc("C", 
     getName(P::in) = (Name::out),
     [will_not_call_mercury, thread_safe, promise_pure],"
{
    Name = (MR_String) strdup(P->name);
}").

main(!IO):-
    createStruct(36, "Mozart", Struct),
    io.format("name: %s\n", [s(getName(Struct))], !IO),
    freeStruct(Struct, !IO).

------------------------------------------------------------------------------------






       
____________________________________________________________________________________
Novo Yahoo! CadĂȘ? - Experimente uma nova busca.
http://yahoo.com.br/oqueeuganhocomisso 

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