[mercury-users] Mercury and C

Ralph Becket rafe at cs.mu.OZ.AU
Tue Nov 12 17:49:24 AEDT 2002


Drirr C., Monday, 11 November 2002:
> Hello,
> 
> I'm writing a program using Mercury and C, however I haven't been able to
> return a string from the c function.
>  
> I have something like this:
>  
>  :- pred buildPoly(int::in, int::in, int::in, int::in, string::out) is det.
>  ...
> :- pragma c_code(buildPoly(VARS::in,TERMS::in,NEG::in,SEED::in,OUT::out),
> [may_call_mercury], "buildPoly(VARS,TERMS,NEG,SEED,OUT);").
> 
>  
>  And then something like this:
>  
>  void  buildPoly(MR_Integer variables, MR_Integer terms, MR_Integer
> negations, MR_Integer seed,  MR_Word result) {
>  ...
>      buffer = (char*)malloc(...);
>  ...
>      *((char **)result) = buffer;
> }

According to "Passing Data to and from C" in the Reference Manual
http://www.mercury.cs.mu.oz.au/information/doc-latest/reference_manual_14.html#SEC126
we have
typedef MR_Char *MR_String;

Also, we have "For output arguments, the Mercury implementation will
pass to the C function an address in which to store the result."

So your result argument should have the signature `MR_String *result',
not MR_Word.  You set up the result by assigning to *result.  The
(referents of) output arguments will contain garbage at the start of the
call.

>  And a result is only returned by the c function either when it can fail or
> when it's a function (not a predicate), hence the void in buildPoly. Am I
> right?

A C implementation of a Mercury predicate or clause should only return a
value (an MR_Integer) if it can fail (0 for failure, non-0 for success.)

> Any suggestions?

You don't want to use malloc; rather use MR_GC_Malloc:
void *MR_GC_malloc(size_t num_bytes)
or MR_GC_malloc_uncollectable:
void *MR_GC_malloc_uncollectable(size_t num_bytes)
These signatures are described in runtime/mercury_memory.h
in the source distribution.

- Ralph
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the users mailing list