[m-users.] foreign_type confusion on how to do it across modules...

Zoltan Somogyi zoltan.somogyi at runbox.com
Sun Jul 14 09:24:20 AEST 2019



On Sat, 13 Jul 2019 23:53:28 +0100, emacstheviking <objitsu at gmail.com> wrote:
> *    % SDL_Rect:- type sdl_rect.:- pragma foreign_type("C", sdl_rect,
> "SDL_Rect", [can_pass_as_mercury_type]).*

If you have that definition in your code, but not ...

> *:- type sdl_rect ---> sdl_rect(x::int, y::int, w::int, h::int).*

... this definition, then only C code knows the structure of this type, and
therefore only C code can create values of this type.

> *  sdl_renderfillrect(Rnd, sdl_rect(0, 50, 200, 100), !IO),*

This means that if you want to be able to write code like that, you will
need to define a Mercury function sdl_rect/4, whose implementation
will be a foreign_proc that allocates memory for a structure and fills in its fields
before returning a pointer to it. (I presume that SLD_Rect is a typedef for a
pointer to a structure type.)

In C, the allocation should be done with the MR_GC_NEW macro,
which is defined in runtime/mercury_memory.h, or its MR_GC_NEW_ATTRIB
variant, which help with memory profiling.

Julien, Peter: I see that the reference manual is silent on how foreign code should
allocate memory whose address is passed to Mercury code. Since you have more
experience with interfacing to foreign language code than I do, could one of you
please take a crack at adding a paragraph about this to the sections dealing
with the interfaces to C, C#, Java and Erlang?

Zoltan.


More information about the users mailing list