int argc, const char * argv[] , why we give these input to main - command-line

Why we give these arguments to main ,searched a lot but couldn't find an answer to clear this doubt.
int main(int argc, const char * argv[])

argc represents the number of arguments passed to the main function.
argv[] represents the arguments passed which are separated by space.
Eg:-
$ ./a.out First Second Third
Program Name Is: ./a.out [argv[0]]
Number Of Arguments Passed: 4 [argc value]
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First
argv[2]: Second
argv[3]: Third
Refer here for more information

Related

Why do XS subs use const char *?

A lot of Perl XS code uses const char * as the return value of an XS sub but never just char *. For example:
const char *
version(...)
CODE:
RETVAL = chromaprint_get_version();
OUTPUT: RETVAL
code from xs-fun
Can someone explain why const is preferred? In my testing, the returned scalar is modifiable whether const is used or not.
It's only for clarity. The chromaprint_get_version function returns a const char *, so the XSUB should be defined with a const char * return type as well. If you have a look at the built-in typemap, it doesn't make a difference whether you use const char *, char *, or even unsigned char *. They all use the T_PV typemap. In all cases, the XSUB will return an SV containing a copy of the C string, which is always modifiable.

Deploy an matlab file to executable

I want to deploy an m file into an executable. I am using mcc command: mcc -m epidemic.m. Epidemic is my function which takes no arguments and returns a vector and write that vector to txt. Mcc creates epidemic.exe and when I am running that exe it creates the txt file however it seems that it doesnt return values (the return value of .exe). I am trying to run the exe from matlab using:
cmd = ['epidemic.exe '];
system(cmd);
It return cmdout " and status 0. How can I take the returned values of the .exe?
When you compile matlab code like:
function [out1, out2] = epidemic(in1, in2, in3)
%[
...
%]
to standalone (mcc -m epidemeic.m), Matlab produces somehow the following pseudo c-code and compiles it to .exe:
int main(int argc, char** argv)
{
// Load compiled code produced by mcc
HMCRInstance* hInst = loadByteCodeProducedByMccFromResources();
// Similar to have wrote in matlab "epidemic(argv[0], argv[1], ...)"
// 1) Without asking for any argument output
// 2) Argument inputs are passed as strings
int errorCode = mclFevalFromExeArg(hInst, "epidemic", argc, argv);
return errorCode; // only indicates if call to 'mclFEvalFromExeArg'
// succeded, it does not relate to out1, out2 at all.
}
NB: If you want to see the exact code produced by mcc, use mcc -W main -T codegen epidemic.m
So, directly compiling to standalone, you cannot work with outputs of your Matlab function. If you need to play around with output arguments of epidemic, either
[Simple solution] Consider saving outputs to files or display them to shell console using disp (NB: you can use isdeployed in your .m file to check if you're running from matlab or from compiled code).
[Advanced solution] Consider compiling your code to shared library (mcc -l epidemic.m) instead of standalone (mcc -m epidemeic.m)
NB: When you compile your code to shared library, mcc will produce a dll that exports the following function:
extern LIB_epidemeic_C_API
bool MW_CALL_CONV mlxEpidemic(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[]);
nrhs/prhs are the number of input arguments and their values (as mxArray type). And nlhs/plhs are the ouput arguments you want to have when calling epidemic. Up to you to do the marshaling between mxArray and equivalent C native type.
EDIT
As you indicate that epidemic returns a vector of values, you can display them from standalone like this:
function [output] = epidemic(v1, v2, v3)
%[
% When called from system cmd line, v1, v2, v3 are passed
% as string. Here is how to convert them to expected type if required
if (ischar(v1)), v1 = str2double(v1); end
if (ischar(v2), v2 = str2double(v2); end
if (ischar(v3)), v3 = str2double(v3); end
...
output = ...;
...
if (isdeployed())
disp(output);
end
%]
An exe does not have a return value, you need to find another way to transport the data back, for example via console outputs or text files. What you get is the error code and error message.

Return variable number of outputs from mex function

Is there any way to return a variable number of outputs from a mex function?
One might pack them into a cell, but I wondered wether there is a way, so that they are expanded directly in the output list. Something like
a = mymex(arg1, arg2);
[a, b, c] = mymex(arg1, arg2, 'all');
Of course you can, just like any other MATLAB function:
test_mex.cpp
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
for (int i=0; i<nlhs; i++) {
plhs[i] = mxCreateDoubleScalar(i);
}
}
MATLAB
>> [a,b,c] = test_mex()
a =
0
b =
1
c =
2
You will have to determine how many arguments to return depending on the inputs/outputs, or issue an error if the function is called incorrectly (not enough input, too many outputs, etc..). The example above just accepts any number of output arguments (including none or zero outputs)
Take comma separated lists, which allow use to call functions in interesting ways:
>> out = cell(1,20);
>> [out{:}] = test_mex()
out =
Columns 1 through 11
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]
Columns 12 through 20
[11] [12] [13] [14] [15] [16] [17] [18] [19]
This is like calling the function with 20 output variables:
>> [x1,x2,...,x20] = test_mex()
EDIT:
Just to clarify, MEX-functions act like regular M-functions defined with variable number of inputs and outputs (think function varargout = mymex(varargin)), and the same rules apply; it is up to you to manage access to inputs and create necessary outputs.
For example the previous code can be written as a regular M-function called the same way as before:
function varargout = test_fcn(varargin)
for i=1:nargout
varargout{i} = i-1;
end
end
The difference is that in MEX-files you could crash MATLAB if you try to access something out-of-range, or try to write output beyond what is actually allocated.
Take this example:
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
for (int i=0; i<30; i++) { // <--- note 30 as value
plhs[i] = mxCreateDoubleScalar(i);
}
}
Calling the above as:
>> test_mex % careful!
will most likely cause an immediate MATLAB crash. While the same thing done in M-code, will just create unnecessary extra output variables that are destroyed after the call.
As #chappjc explained in his answer, for MEX-files you are always guaranteed to have space for at least one output (plhs is an array of mxArray* of length 1 at a minimum, so it's safe to assign plhs[0] no matter what). If the caller specifies a LHS variable then the output goes into it, otherwise the output is assigned to the special ans variable (of course you can still assign nothing, in case of zero outputs).
The opposite case of not assigning enough output variables is fortunately caught by MATLAB, and throws a regular catch-able error with ID MATLAB:unassignedOutputs (in both MEX and M-functions).
Also, accessing out-of-range inputs will cause an access violation (MATLAB will inform you of that with a big scary dialog, and the prompt will turn to "please restart MATLAB" message). Doing the same in regular M-code, will just throw a regular error "Index exceeds matrix dimensions.", nothing serious!
As you can see, it is very easy for things to go wrong in MEX world (in an unrecoverable way), so you have to pay special attention to validating input/output arguments.
The syntax for calling a MEX function is identical to any other MATLAB function. However, internal to the MEX function, the number of in/out arguments used is determined by the first and third arguments to mexFunction (usually named nlhs and nrhs, can be anything).
Declaration of mexFunction in mex.h (around line 141 in R2014b):
/*
* mexFunction is the user-defined C routine that is called upon invocation
* of a MEX-function.
*/
void mexFunction(
int nlhs, /* number of expected outputs */
mxArray *plhs[], /* array of pointers to output arguments */
int nrhs, /* number of inputs */
const mxArray *prhs[] /* array of pointers to input arguments */
);
This is not unlike the syntax for the standard main functions for C/C++ command line executables, but there are notable differences. Unlike the native command line version (int main(int argc, const char* argv[])), the count and pointer array does not include the name of the function (argv[0] is usually the name of the executable program file), and with mexFunction there are parameters for output arguments as well as input.
The naming for nlhs and nrhs should be clear. HINT: In mathematics, an equation has a left hand side and a right hand side.
An important but easily overlooked quality of mexFunction I/O handling pertains to MATLAB's special ans variable, the place where function outputs (often) go if you don't assign to a variable. In a MEX file, you need to remember the following when checking nlhs. If nlhs=0, you can and must still write to plhs[0] for ans to be used. It's documented, just barely, in Data Flow in MEX-Files. Consider what happens with the following code:
// test_nlhs.cpp
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
for (int i=0; i<nlhs; ++i)
plhs[i] = mxCreateDoubleScalar(i);
}
Outputs:
>> test_nlhs
>> [a,b] = test_nlhs
a =
0
b =
1
There's no output to ans because the logic with nlhs prevents it from assigning to plhs[0]. Now this code:
// test_nlhs.cpp
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nlhs==0) {
mexPrintf("Returning special value to ""ans"".\n");
plhs[0] = mxCreateDoubleScalar(-1);
} else {
mexPrintf("Returning to specified workspace variables.\n");
for (int i=0; i<nlhs; ++i)
plhs[i] = mxCreateDoubleScalar(i);
}
}
Outputs
>> test_nlhs
Returning special value to ans.
ans =
-1
>> [a,b] = test_nlhs
Returning to specified workspace variables.
a =
0
b =
1
It's certainly doesn't have to be a special value, and it should usually be the same first output argument, but I'm illustrating how you recognize the calling syntax.

store string in char array assignment makes integer from pointer without a cast

#include <stdio.h>
int main(void){
char c[8];
*c = "hello";
printf("%s\n",*c);
return 0;
}
I am learning pointers recently. above code gives me an error - assignment makes integer from pointer without a cast [enabled by default].
I read few post on SO about this error but was not able to fix my code.
i declared c as any array of 8 char, c has address of first element. so if i do *c = "hello", it will store one char in one byte and use as many consequent bytes as needed for other characters in "hello".
Please someone help me identify the issue and help me fix it.
mark
i declared c as any array of 8 char, c has address of first element. - Yes
so if i do *c = "hello", it will store one char in one byte and use as many consequent bytes as needed for other characters in "hello". - No. Value of "hello" (pointer pointing to some static string "hello") will be assigned to *c(1byte). Value of "hello" is a pointer to string, not a string itself.
You need to use strcpy to copy an array of characters to another array of characters.
const char* hellostring = "hello";
char c[8];
*c = hellostring; //Cannot assign pointer to char
c[0] = hellostring; // Same as above
strcpy(c, hellostring); // OK
#include <stdio.h>
int main(void){
char c[8];//creating an array of char
/*
*c stores the address of index 0 i.e. c[0].
Now, the next statement (*c = "hello";)
is trying to assign a string to a char.
actually if you'll read *c as "value at c"(with index 0),
it will be more clearer to you.
to store "hello" to c, simply declare the char c[8] to char *c[8];
i.e. you have to make array of pointers
*/
*c = "hello";
printf("%s\n",*c);
return 0;
}
hope it'll help..:)

Matlab mex c: strange calculation error with long double

I've noticed a problem on some C code that I'm writing where when I multiply two long doubles I sometimes get lower than expected accuracy. I've isolated an example below, note that this is an mex file for use in matlab. Repeating exactly the same code in pure c results in the expected behaviour.
#include <mex.h>
#include <stdint.h>
typedef int32_t q0_31; // 32 bit signed fixed point number with 31 fractional bits
// conversion to long double from q0_31
long double q0_31_to_ldouble(q0_31 d) {
return d/2147483648.0L;
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mwSize nInputs = 0;
mwSize nOutputs = 0;
q0_31 b;
long double b_ld;
/* check for proper number of arguments */
if( nrhs!=nInputs )
mexErrMsgIdAndTxt("filter_interface:nrhs","wrong number of inputs!");
if( nlhs!=nOutputs )
mexErrMsgIdAndTxt("filter_interface:nlhs","wrong number of outputs!");
// random value for b
b = 0x81948b0e;
// convert to long double directly
b_ld = b/2147483648.0L;
mexPrintf("Inline calculation...\n");
mexPrintf("b_ld:\t%0.16LA\n",b_ld);
mexPrintf("b_ld^2:\t %0.16LA\n",b_ld*b_ld);
// repeat with sub function
b_ld = q0_31_to_ldouble(b);
mexPrintf("Exactly the same with sub function...\n");
mexPrintf("b_ld:\t%0.16LA\n",b_ld);
mexPrintf("b_ld^2:\t %0.16LA\n",b_ld*b_ld);
}
After compilation, this is the output I get from the code:
Inline calculation...
b_ld: -0XF.CD6E9E4000000000P-4
b_ld^2: 0XF.9B7D0E4BEE0D3100P-4
Exactly the same with sub function...
b_ld: -0XF.CD6E9E4000000000P-4
b_ld^2: 0XF.9B7D0E4BEE0D0000P-4
It is totally bizarre, the value returned by the function is exactly the same as the inline calculation. Yet when I square it I get a different result.
As I only get this behaviour in the mex and not when I compile the same code directly with gcc I thought it might be due to some strange compiler flag that matlab uses. But I have not been able to find anything.
Any ideas? Can anyone replicate?
MATLAB Version: 7.14.0.739 (R2012a)
gcc: 4.8.1-10ubuntu9