3

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.

Jay Sullivan
  • 17,332
  • 11
  • 62
  • 86
tiwo
  • 3,238
  • 1
  • 20
  • 33

2 Answers2

5

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.

M. S. B.
  • 28,968
  • 2
  • 46
  • 73
  • Great! Exactly what I was looking for, this helped me solving this. Sorry if my question has been a stupid one (now that I see the answer.) – tiwo Jun 17 '12 at 08:44
1

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];
src
  • 541
  • 2
  • 6