3
votes

How to call a void *function(...) from Fortran?

I am currently trying to call a few C functions from Fortran. I have done so before, but I have called only my own functions. For example, to call:

void add(int *csum, int *ca, int *cb) { *csum = *ca + *cb; }

from Fortran, I have used:

INTEGER :: fsum, fa, fb
CALL add(fsum, fa, fb)

This works fine. Now I have a couple of functions roughly like:

void *create_obj(void);
void use_obj(void *obj);
void free_obj(void *obj);

or even:

struct private_struct; /* defined somewhere else */
struct private_struct *create_p(void);
void use_p(struct private_struct *p);
void free_f(struct private_struct *p);

where the struct is private, i.e., I have no knowledge of its members.

Question: How can I get the return values into Fortran? I do not really need to access them, but I must store them somehow during their create...use...destroy lifecycle.

2

2 Answers

5
votes

You can create the object in C, pass a pointer to it to Fortran, then pass that pointer to C routines. Finally, call a C routine to free the memory. The ISO C Binding provides the Fortran type C_PTR.

1
votes

Instead of returning a pointer to the object you can keep it in an array (or other container) inside the C library and return and index into the array (or whatever it fits your container).

int create_obj(); // returns the obj_id
void use_obj(int *obj_id);
void free_obj(int *obj_id);

You will have to keep count of what elements of the array are being used. Something like

struct Entry {
    bool used;
    struct Obj value; 
}
Entry objects[100];