Reputation: 674
I have the source file of a big module written in fortran90
with some type definitions, some interfaces, some functions and subroutines. I am able to compile it and to use it inside a normal fortran
program.
But since I have always used C/C++
and I don't know so much of fortran
I would like to use this module inside a C/C++
program. That is using its data types and calling its functions/subroutines on them.
Is it possible? How can I do this? What are the various steps I have to achieve? Are there some exhaustive tutorials on the web (I didn't find so much with a brief google search..)
Upvotes: 0
Views: 153
Reputation: 180201
Fortran 2003 adds specific provisions for interoperability with C. You can find a run-down in the GCC docs. If your Fortran code does not use those features, however, (as indeed it probably doesn't) and you are not prepared to modify it to do so, then the answer depends strongly on your Fortran and C tool chains. Some issues involved include
char *
and pass the length as a separate argument, but other arrangements have been employed. Also, the length argument may follow immediately after the pointer, or it may be append at the end of the argument list.int
and double
to Fortran data types depends somewhat on the compilers involved. It is not guaranteed that all types provided by one compiler have analogous types among those known to the other compiler.That's not an exhaustive list, but it covers most of the common issues. Which of them you need to deal with depends on the packages you are trying to connect.
Previous to F03, Fortran / C interop was typically provided on a product-by-product, toolchain-specific basis. Often a set of specific interface functions was provided on one side or the other, or both. There is still a great deal of such code out there, and it might be a good strategy for you, too. Also, there are tools that try to help sort out the mess. The GNU Autotools have some support for it, for instance, covering much more than just the GNU toolchain. Alternatively, you may need to inspect some object files to determine how to approach some of those issues.
Upvotes: 4
Reputation: 33273
The search call fortran from c gave me several links to various tutorials and examples.
Some highlights:
Fortran calls are by reference, so you get to use pointers/the address-of operator a lot.
Fortran routines are usually exported with some simple name mangling. You can either find out by reading the manual or you can use nm f.o
, where f.o is a compiled fortran file.
Using the routine names obtained you need to create a C header file with declarations for the routines you want to call.
When linking you need to link with the fortran library, -l<name of fortran lib>
.
Upvotes: 0