C calling Fortran subroutine - fortran90

I am new to the site, and this looks like it may be a place to get some tips and help if any.
I am learning about "C calling Fortran subroutine", I have knowledge with C but not too much with Fortran.
Plus side: I've looked at some examples, and was able to compile a few.
Negative side: I am somewhat lost. I have a main program which can be designed using C or Fortran 90, and print_matrix.f and print_matrix.c.
Within the main.c program,
- populate array of 1-9 of a matrix size 3 by 3
- call the c function
- call the fortran subrountine
I already have the populated side(it may not be accurate), but I am stuck on the subrountine. The output of fortran and C has to be the same which will output through the print_matrix.f90 and print_matrix.c using makefile. I need help with the calling subrountine part, I just don't know where to begin with that :(
I just need help, any will be appreciated.

Honestly, it's a little hard to tell exactly what your problem is. But here's an example that works on my linux machine:
callf.c:
#include<stdio.h>
int main(int argc, char **argv) {
int i=0;
increment_(&i);
printf("%d\n",i);
return;
}
increment.f90:
subroutine increment(n)
integer n
n=n+1
return
end subroutine
Compiled with:
gcc -c callf.c
gfortran -c increment.f90
gcc callf.o increment.o -lgfortran
Result:
> ./a.out
1
The two hard parts are 1) getting the exact name of the function call and 2) knowing what flags are needed to link the two codes. Re: 1) I knew to use "increment_" because, after compiling my FORTRAN code, I ran the "nm" utility on increment.o and found the name of the object was "increment_". On some systems, you might see "INCREMENT", "_increment", or all sorts of other things. Re: 2) Information should be available for whatever compiler you are using. It varies alot.

Related

In C can you pass a macro with multiple values to a function

I have a messaging function that takes a variable amount of arguments because it supports string formatting in the same way printf does. My plan was to then define message code and messages with a single #define and be able to call this function by passing it a single argument for something that is tightly related.
Here is the message macro:
#define MSG(a, b, ...) message(__FILE__, __LINE__, a, b, __VA_ARGS__);
And here is an example of the message code and string define:
#define MSG_INIT 0000,"%s INITIALIZED SUCCESSFULLY"
The issue is occurring when I try to make a call in the form of:
MSG(MSG_INIT);
My IDE is giving me an error along the lines of:
'Expands to message("file.c", 1, 0000, "INITIALIZED SUCCESSFULLY",);
where the last ',' is causing the issue.
I was expecting to see:
'Expands to message("file.c", 1, 0000, "INITIALIZED SUCCESSFULLY");
If I change the call to:
MSG(MSG_INIT,NULL);
All is good but I'd rather not pass the NULL because the point of the MSG_INIT define in the first place was to pass less parameters. There are messages that make use of the __VA_ARGS__ (Example: #define MSG_CONNECT 0001,"CONNECTION TO [%s] ESTABLISHED" with matching call MSG(MSG_CONEST, server_ip);) so getting rid of that is not an option. I am just looking for the best way to fix this problem and I'm aware a lot of people suggest staying away from the preprocessor but this was the best solution I thought of.
I'm aware a lot of people suggest staying away from the preprocessor ...
I wonder why that is. Could it possibly be for the same reason you had to ask this question? :-)
Honestly, the pre-processor should be limited pretty much to including header files and doing conditional compilation. Anything else that it used to be used for, such as:
#define RC_OK 0
#define RC_NOMEM 1
#define HALF_OF(x) x / 2
is far better done with enumerations or functions.
The days of function-like macros should be put behind us, especially since modern compilers can quite easily out-optimise most hand-crafted code, and without subtle errors creeping in such as with that HALF_OF macro above (do not use it, I specifically made it buggy to illustrate a point).
It's really just a text substitution thing, one which understands the lexical elements, but not the full grammar of C. The fact that you have to perform what I call "macro gymnastics" to get it to do anything other than simple stuff is reason enough to steer clear. Use functions for this, it'll make your life a lot easier.
And apologies for not solving your specific issue, I just think any solution using the pre-processor is going to be half-baked at best. But there's plenty of precedent on SO for answering the question "How do I X?" with "Don't X, it's better to Y." Think of writing an accounting package in assembler, an operating system in object-oriented COBOL, or anything in Pascal :-)
But, if you really wanted to stick to macros against my advice, you could try starting with something like:
#include <stdio.h>
#define MSG(fmtStr, ...) printf("%s:%d> " fmtStr, __FILE__, __LINE__, __VA_ARGS__)
#define MSG_INIT "Initialised %s\n"
#define MSG_TERM "Terminated %s with values %d and %d\n"
int main(void) {
MSG("%f\n", 42.3);
MSG(MSG_INIT, "something");
MSG(MSG_TERM, "something else", 7, 42);
}
I think that's portable, and it allow you to put the heavy lifting into MSG and using a separate format string and parameters for the rest of the stuff:
testprog.c:8> 42.300000
testprog.c:9> Initialised something
testprog.c:10> Terminated something else with values 7 and 42

MATLAB script use in System verilog using SNPS VCS tool

I have coded an algorithm using MATLAB R2019 script and i want it to be called in an System verilog file i.e The output generated by the matlab script is actually to be fed into the testbench written using SV. I dont want to use HDL coder tool as the algorithm is quite complex and re-coding it in SV/ C is quite difficult. I use synopsys VCS tool for compilation and elaboration.
My question is :
1. Is it possible that a MATLAB script to be called in testbench written in SV ? I've heard about DPI, but not much idea on it, or worked on it.
2. Can the output of the MATLAB script stored in a separate file, let's say for example a text file and i can call that file in my SV test bench.?
To answer your questions in order, it is indeed possible.
You need to do the following:
In SV, import a C function (extern DPI-C) that you will call as required. Say we call this callMatlabFn
In C, define an extern function called callMatlabFn. This will then actually call your matlab fn. Have a look here for calling matlab in C : https://www.mathworks.com/help/matlab/matlab_external/call-matlab-functions-from-c-1.html
Note, you could return data via DPI but that may have a different meaning. It may be best to return any data in SV via reference in an output arg to the imported fn.
Finally, text File I/O in SV is implemented via the following system tasks:
$fopen (file_name) ;
$fclose (file_name) ;
$fdisplay (arguments) ;
$fwrite (arguments) ;
$fstrobe (arguments) ;
$fmonitor (arguments) ;
$readmemb ("file", memory_identifier [,begin_address[,end_address]]) ;
$readmemh ("file", memory_identifier [,begin_address[,end_address]]) ;

How to read a simple expression in Fortran?

In the Fortran program, is it possible to read an expression including the variables ?
For example, the input file is (if necessary, we can change the input form of the expression,e.g.,the binary form),
2(a-4b)
It should be noted that the input expression has a very simple form and it only contains integer or fraction or some variables,like the following in the list,
{0,232,-2/5a,3a-b,b/9}
Here 2a means 2*a
The Fortran program is
Program test
implicit none
real(kind=8)::a,b,exp
a=10.
b=3.
! open file and read the input expression
! that is, exp=2*(a-4*b)
write(*,*) exp ! we can get exp=-4.0
end program
For the complicated expressions, it is obviously not a good idea for Fortran. I just want to know, in this simple input expression case, is it possible to find a better way ?
A site with tests of three expression evaluators in Fortran is http://www.angelfire.com/ab5/extensao/report.htm . Only the link to the "Brazilian" one works.
There is also a Sourceforge project fparser http://fparser.sourceforge.net/ .
Fortran cannot do this unless you write code that can parse the arbitrary expression, substitute and solve, which is a bit of work (see the comment below for details). Fortran is compiled and there is no way to load source on the fly, compile and run it, which is essentially what you are asking. You might look into a language such as Lisp where doing this is should be somewhat trivial. Likewise any scripted language will have facilities to evaluate code, which can do what you are asking.

Convert / translate Fortran f77 code to C or Matlab / Octave

I have an old piece of Fortran f77 code that I would like to understand and edit for future reuse. For that purpose, I would like this code to be translated to either C or Matlab / Octave language. I have found an instance of f2c exe online, but it wouldn't run because of inappropriate OS ( my OS is Win 7 x64, f2c wanted older x32 ).
My main concern is being able to understand the code. Translation in terms of execution efficiency is not of importance. I am open to any suggestion, apart from learning Fortran 77. I am aware of that option myself, but would do it only as a last resort. Thank you.
Just learn Fortran. The output of machine-translated code may well be functionally correct and suitable for compilation and execution, but it's going to be really hard to understand and maintain. (Just look at what generated code targeting a single language, like the output of a GUI builder wizard, looks like.) In particular, while Matlab is built on Fortran, its idioms at the M-code level are different enough that it would be pretty incomprehensible. If you already know C or any other Algol-like language, picking up Fortran is not that hard. And the idioms and features that are particular to Fortran – that is, the new stuff you'd have to learn – are probably going to be especially weird and incomprehensible when sent through a translator.
The one translator that might actually be useful is a Fortran 77 -> Fortran 90 translator. The modern '90 dialect would be easier to learn and more succinct, and since the translation is within the same language family the output probably wouldn't be too ugly.
Since are using Octave, you can call Fortran code, there is no need to rewrite it. You will need to write a very simple C++ wrapper to it but Octave already provides macros to do all of the hard work. It is all documented on the manual. Actually, Octave itself calls on many fortran subroutines, so this is perfectly normal.
If you want to modify it, you should be learning Fortran then.

How can I reference #defines in a C file from python?

I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python?
Note: I know I can just open the header file and parse it, that would be simple, but if there's a more pythonic way, I'd like to use it.
Edit:
These are very simple #defines that define the meanings of bits in a mask, for example:
#define FOO_A 0x3
#define FOO_B 0x5
Running under the assumption that the C .h file contains only #defines (and therefore has nothing external to link against), then the following would work with swig 2.0 (http://www.swig.org/) and python 2.7 (tested). Suppose the file containing just defines is named just_defines.h as above:
#define FOO_A 0x3
#define FOO_B 0x5
Then:
swig -python -module just just_defines.h ## generates just_defines.py and just_defines_wrap.c
gcc -c -fpic just_defines_wrap.c -I/usr/include/python2.7 -I. ## creates just_defines_wrap.o
gcc -shared just_defines_wrap.o -o _just.so ## create _just.so, goes with just_defines.py
Usage:
$ python
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import just
>>> dir(just)
['FOO_A', 'FOO_B', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_just', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic']
>>> just.FOO_A
3
>>> just.FOO_B
5
>>>
If the .h file also contains entry points, then you need to link against some library (or more) to resolve those entry points. That makes the solution a little more complicated since you may have to hunt down the correct libs. But for a "just defines case" you don't have to worry about this.
You might have some luck with the h2py.py script found in the Tools/scripts directory of the Python source tarball. While it can't handle complex preprocessor macros, it might be sufficient for your needs.
Here is a description of the functionality from the top of the script:
Read #define's and translate to Python code.
Handle #include statements.
Handle #define macros with one argument.
Anything that isn't recognized or doesn't translate into valid
Python is ignored.
Without filename arguments, acts as a filter.
If one or more filenames are given, output is written to corresponding
filenames in the local directory, translated to all uppercase, with
the extension replaced by ".py".
By passing one or more options of the form "-i regular_expression"
you can specify additional strings to be ignored. This is useful
e.g. to ignore casts to u_long: simply specify "-i '(u_long)'".
#defines are macros, that have no meaning whatsoever outside of your C compiler's preprocessor. As such, they are the bane of multi-language programmers everywhere. (For example, see this Ada question: Setting the license for modules in the linux kernel from two weeks ago).
Short of running your source code through the C-preprocessor, there really is no good way to deal with them. I typically just figure out what they evalutate to (in complex cases, often there's no better way to do this than to actually compile and run the damn code!), and hard-code that value into my program.
The (well one of the) annoying parts is that the C preprocessor is considered by C coders to be a very simple little thing that they often use without even giving a second thought to. As a result, they tend to be shocked that it causes big problems for interoperability, while we can deal with most other problems C throws at us fairly easily.
In the simple case shown above, by far the easiest way to handle it would be to encode the same two values in constants in your python program somewhere. If keeping up with changes is a big deal, it probably wouldn't be too much trouble to write a Python program to parse those values out of the file. However, you'd have to realise that your C code would only re-evaluate those values on a compile, while your python program would do it whenever it runs (and thus should probably only be run when the C code is also compiled).
If you're writing an extension module, use http://docs.python.org/3/c-api/module.html#PyModule_AddIntMacro
I had almost exactly this same problem so wrote a Python script to parse the C file. It's intended to be renamed to match your c file (but with .py instead of .h) and imported as a Python module.
Code: https://gist.github.com/camlee/3bf869a5bf39ac5954fdaabbe6a3f437
Example:
configuration.h
#define VERBOSE 3
#define DEBUG 1
#ifdef DEBUG
#define DEBUG_FILE "debug.log"
#else
#define NOT_DEBUGGING 1
#endif
Using from Python:
>>> import configuration
>>> print("The verbosity level is %s" % configuration.VERBOSE)
The verbosity level is 3
>>> configuration.DEBUG_FILE
'"debug.log"'
>>> configuration.NOT_DEBUGGING is None
True