matlab in C C++ and C C++ in matlab [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
It seems that are several ways to call matlab in C C++ and to call C C++ in matlab. While I try to list them here, please point it out If I miss something.
To call C C++ in matlab, there are also two methods. The first one is to call functions in C shared libraries. The second one is to build C C++ code into binary MEX-files, which will be called from the MATLAB command line. For the first method, are the C shared libraries are just general ones, i.e. without change to their C code for matlab and compiled from general C compiler like gcc?
To call matlab code in C C++, there are two methods available. The first one is Matlab engine. The second one is to use MATLAB Compiler mcc to create C or C++ shared libraries from your MATLAB code.
Besides matlab and C C++ can communicate via writing and reading data to and from some file (e.g. mat file, text file).
Having more than one ways to accomplish each of the goals here, could you tell me what cases are best for using which of them? i.e. calling functions in C shared libraries VS building C C++ code into binary MEX-files, Matlab engine VS compiling Matlab code into C C++ shared library.
Thanks and regards!

I only have expreience with calling C or C++ functions from MATLAB. It looks to me like the only difference between calling functions in a shared library and calling functions from a MEX file is that with a shared library, you have to call the function with 'calllib' which is a command line type function and MEX functions allow you to call functions as if they are built-in functions so the interface is a little cleaner.
My suggestion is to use MEX files if
You are using C++ (you may have to write a wrapper to use a C++ in a shared library)
You are using MATLAB as the glue for a large number of optimized C or C++ routines. You'll want to be able to call them cleanly.
Use shared library if
You already have an existing C library that can be used without modification.
You only need a small number of calls to C functions.
Really, it comes down to the interface. I personally prefer the MEX file route because it provides the cleanest interface from MATLAB to your C or C++ function. You can call it like just another function with standard MATLAB types. With a shared library, you may have to do some data formatting before calling the library function

I think the methods you've named are correct (it's been a while since I've used them)
The matlab C-compiler isn't really special; it is possible to use different compilers. See link list of supported compilers. This does not include gcc, but MS Visual studio is included. You'll run into issues when linking with the supplied libraries.
Basically: calling matlab from C is something you'd do if you need a tight interface; for instance if you want to synchronise 2 tools, or your S-function (simulink) requires additional information. But then, such a file is propably called by Matlab/simulink in the first place.
Calling c from matlab is what you want to do if you write your own S-functions or extensions to matlab.
The choice between C and C++ is yours; if you start from a blank sheet I suggest you use C++; you don't need to use the complete functionality but it allows more freedom. Also more libraries tend to be available for C++ nowadays.
C is the language of choice if you need to migrate to very different environments; i.e. to compile C to DSPs for instance. Or if you have got legacy code in C to start from. Mixing C and C++ is possible, but a can be a bit cumbersome; I'm sure you'll find topics on StackOverflow on this subject alone.

Related

How does code from different languages get integrated in the same platform? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
First and foremost, I'm no expert in software, and I realize this question might be as vague as it gets (it's just a curiosity), and get ready to read some barbaric guesses from my part!
The question came up from reading an article on how Linux's developers were implementing Rust into their OS (https://www.zdnet.com/article/linus-torvalds-on-where-rust-will-fit-into-linux/).
What does it even mean to implement Rust in their OS? Do they have some compiled code written in C that calls compiled code that resulted from writing in Rust? I don't see how this can efficiently be done, as you'd have different compilers probably being unable to optimize code, since, along the way, it's calling "foreign" code. I imagine the situation gets worse if you throw a language like Python or Java into the mix, which aren't precompiled. Now you would have JVM or PVM running together with compiled code, which, I imagine, would be highly impractical. One approach I can conceive, is if you see all these things as separate processes, and you'd simply have code from one language starting a process that corresponds to code from another language, but again, I imagine that wouldn't be very efficient...
Again, I realize I could've been more direct, but I'm not looking for a specific answer which addresses a problem, but rather general insight on how different languages can get used together. Thanks for understanding!
Typically when compiling a source file we have a set of options for outputs generated by the compiler, like creating a binary application from the main function, a statically linkable binary or a dynamically linkable library, or in other cases, source to source transformations.
The kernel is written in C, and to be able to compile large codebases like the kernel, we often decide to compile each, or a set of source files (the proper term would be translation unit https://en.wikipedia.org/wiki/Translation_unit_(programming)) into a statically linked library or object files. Once we've gathered all of the object files and statically (or shared) linked libraries we can link these together and produce a final binary/library.
When we're talking about integrating Rust code into the kernel, we're talking about using statically linked libraries from C in Rust and vice versa. The process of calling code produced from other compilers or languages is named Foreign Function Interface, or FFI.
There are many details and challenges with FFI including ABIs or name mangling to name a few. ABI, or application binary interface is one of the issues mentioned in your article. Unlike C, Rust does not have a stable ABI yet, meaning there's no guarantee the symbols in the static library compiled from Rust won't have different names or data layouts in the future. This means that code compiled using Rust's compiler may not be compatible with previous Rust compiler outputs which would require the C code to be updated every time there's an ABI change.
Here's how a C program is traditionally compiled:
Each source file is compiled - separately! - into an object file, which contains machine code, and placeholders for connecting all the object files together.
All the object files are joined together and the placeholders are filled in.
If you can generate some of those object files using Rust instead of C, the C compiler can't tell the difference. It's no different from a different C file!
You need to make sure the functions that cross the language barrier need to be valid functions for both languages. For example, you might not be able to pass structures as arguments, or return structures, if that's not valid in Rust (I don't actually know) - you might only be able to use primitive values, like ints and floats and pointers. If the Rust machine code expects float variables to be in certain registers, but the C machine code puts them in different registers, you might not be able to pass floats. Or you might have to put a special hint to one or the other compiler, to say "the argument goes in this register, dummy!" If the Rust compiler people didn't cooperate with the C compiler people, you are likely to run into a few of these kinds of problems, but with a bit of luck, they can all be worked around.
Since the function needs to be valid in both languages, you also need to write a C header file. You can't #include a Rust file - well you can, but it won't work - so you need to write the function declarations again in C syntax so the C compiler can understand what they are.
For languages which require VMs, it's complicated in a different way.
Usually these languages are so different from C that you can't just link together the machine code. Instead you have to use the VM's API to initialize the VM, load the code, and call the code. Something like this:
// not real code, just an illustration of how it could work
// How C starts a JVM and calls a Java method (a Java function)
void run_jvm() {
jvm_t *jvm = create_jvm();
jvm_class_t *main_class = jvm_load_class(jvm, "Main.class");
jvm_method_t *main_method = jvm_get_method(jvm, main_class, "main", NULL);
jvm_call(jvm, main_method, NULL, NULL);
delete_jvm(jvm);
}
// how Java calls a C function
void Java_HelloPrinter_printHello(jvm_t *jvm, jvm_object_t *this, jvm_args_t *args) {
printf("Hello world! My argument is %d\n", jvm_args_get_int(args, 1));
}
// how the method is declared in Java
public class HelloPrinter {
public static native void printHello(int i);
// ^^^^^^
// this means it's a C function
}
In Python or Lua, being more dynamic languages, the interpreter doesn't look for things for you. Instead, you put your functions into variables before you run any of your Python code.
// not real code, just an illustration of how it could work
// How Python calls a C function
void printHelloFunction(pvm_t *pvm, pvm_args_t *args) {
printf("Hello world! My argument is %d\n", pvm_args_get_int(args, 1));
}
// How C starts a PVM and calls a Python method
void run_python() {
pvm_t *pvm = create_pvm();
pvm_variable_t *var = pvm_create_global_variable(pvm, "printHello");
pvm_set_variable_as_c_function(pvm, var, &printHelloFunction);
pvm_load_module_from_file(pvm, "main.py");
delete_pvm(pvm);
}
These languages are not on equal footing with C, but Rust is, because Rust compiles to machine code. If you could run Java or Python code outside of a VM, they could be on equal footing. There used to be a compiler called gcj which would compile Java into machine code, but it's no longer maintained. Someone could write one, although it wouldn't run most Java programs, because a lot of those programs need to do stuff with the VM (like reflection).

python "print" like function in c [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am new to C and I use to code in python, and I usually print too much variables and text to test my code and printf statement is irritating sometimes. I want to write a function in c which works exactly like print function in python.
I am facing two problem while writing the function.
I want to take n number of arguments as input to the function.
I want to take any data type as input to the function,
for Eg: print(12); print("hello"); print(123.12) should not raise error.
What have I done so Far
I found solution for taking n number of arguments using <stdarg.h>, but I have to specify the data type of the first argument which is not what I want.
"generic selection" Macros can be used to call different function on different data type of argument passed but not sure how it can be done, here is the link which I used for reference.
I want to write a function in c which works exactly like print function in python.
You simply cannot do that (because of type erasure : at runtime, type information is lost in C). Read Modern C then see this C reference.
In practice, you'll better write one function per datatype in C to print it. So it would be void print_int(int); to print an integer, void print_double(double); to print a double, etc. Once you have a collection of such functions you might use _Generic inside a macro (but that is rarely useful; it can handle a finite set of types).
Study for inspiration the source code of existing open source C software on github or elsewhere. Look for inspiration inside the source code of GNU bash, sqlite, GTK or GNU bison (and perhaps inside the source code of Python; half of the Python interpreter is coded in C)
Read also the documentation of your C compiler, e.g. GCC. So compile with all warnings and debug info: gcc -Wall -Wextra -g then use the GDB debugger.
Perhaps you want to implement some tagged union abstract data type in C. Then take inspiration from GNU guile or the runtime of Ocaml and dive inside their source code.
Once you are more familiar with C, read some C draft standard, e.g. n2176
Consider using Frama-C or the Clang static analyzer.
Consider also sometimes generating some C code, like SWIG does.
Budget weeks of work.

Is there any difference between a mex file and a function called with coder.ceval?

related
My goal is to use a mix of C code and Matlab code, and ultimately have the whole thing run in C by using the Coder tool.
I've found 2 ways of incorporating C into Matlab, writing a Mex file, and using coder.ceval on a C program.
Is there any difference in these 2 methods, beyond just calling syntax?
I'll compare creating a hand-written MEX file against using MATLAB Coder to integrate custom C code using coder.ceval.
Similarities
In both cases, a MEX file can be produced that you can call in MATLAB like any other MATLAB function. A hand-written MEX function will be compiled using the mex command from C source code you write. With MATLAB Coder the MEX file will be automatically generated from MATLAB code that calls your C code via coder.ceval using either the codegen command or the MATLAB Coder App.
Some Basic Differences
(note I use C throughout, but C++ can be used for MEX files as well)
When writing a MEX file, it is necessary to manually move your data between mxArray values and native C types. You'll need to use the MEX library and the C/C++ Matrix Library to do this. If coder.ceval is used, a MEX file can be auto-generated from your MATLAB code that does this data marshalling for you.
A single hand-written MEX file can be made to work with a variety of MATLAB data types. MATLAB Coder requires the type, size (arrays can also be made variable-size), and complexity of each argument to be declared. For example, if you want a MEX file that takes double and single values for a given input, then one MEX file must be generated for each input type.
With a handwritten MEX file, once the data is retrieved from the mxArray values provided by MATLAB, arbitrary C code can be written to manipulate it. coder.ceval requires that you write MATLAB Coder compatible MATLAB code to call the C functions using the external code interfaces it provides. For functions with simple interfaces, e.g. those taking numeric arrays, strings, etc., this can be simple. For those that take other datatypes, more advanced tools like coder.opaque, coder.cstructname and custom enumeration definitions must be used which can take time. One needs to weigh the cost of developing this interface for MATLAB Coder versus learning and using the MATLAB libraries mentioned in the first bullet.
If you eventually want to use the code in C outside of MATLAB, with MATLAB Coder and coder.ceval, the target can simply be changed from MEX to a standalone target like a static or dynamic library or executable. With a handwritten MEX file, one typically factors the C code so that the MEX interface, mexFunction, is separate from the C functional kernel. Then, this kernel can be called outside of MEX. If you are planning to use MATLAB Coder anyway, you'll have to integrate the MATLAB Coder code with this kernel somehow.
If the code is to be used with MATLAB Coder eventually, calling MEX files using Coder when the target is MEX requires using coder.extrinsic. They also cannot be called directly in standalone targets. Instead, the C computational kernel underlying the MEX file needs to be integrated with the generated code either during code generation using coder.ceval or after code generating using a traditional C development environment.
Factors to Consider When Deciding
Do the benefits of integrating the C code early using MATLAB Coder and having the MEX interface auto-generated outweigh the work required to use the MATLAB Coder external code interfaces versus a hand-written MEX file?
Is integrating the external C code using coder.ceval easier or harder than writing a MEX file that exposes it to MATLAB and then later integrating your MATLAB Coder generated code with the computational kernel underlying your MEX file?

Call MATLAB function from a C program [duplicate]

I have some code that plots triangles in MATLAB.
I need to be able to somehow execute this code from my C program which generates these points.
Is that possible? How can it be done?
Just a thought:
Can I somehow embed MATLAB code in C, so that it can compile on a C compiler?
The Mathworks site has full details; a demo video of calling the Matlab engine from C, and also the Matlab to C Compiler.
As mentioned previously by answerers, you can call a live copy of MATLAB from C via the MATLAB Engine interface.
If the end-product needs to be used where there is no live copy of MATLAB, you can deploy the application using MATLAB Compiler. However, MATLAB Compiler does not, as another answer has suggested, convert MATLAB programs into C code (and hasn't done for a few versions now). Instead, it archives and encrypts your MATLAB program, and packages it into an executable or shared library that executes against the MATLAB Compiler Runtime (shareable royalty-free). The executable or shared library can then be called from C.
Alternatively you could go the other way around, and call your C code from MATLAB, using either loadlibrary or MATLAB's MEX interface.
Update: As of release R2011a, you can also use MATLAB Coder to generate C code directly from a subset of the MATLAB language.
Look at this presentation about integrating MATLAB Algorithms in C or C++ Applications http://www.mathworks.com/videos/integrating-matlab-algorithms-in-c-or-c-applications-86431.html

Interfacing MATLAB with C/C++ programs

Hi I wanted to know how to use MATLAB as an external solver from a C program. Specifically in my code I wish
to solve several linear systems of the form Ax=b.
I have heard that to go the other way namely Calling C functions in a MATLAB routine one uses MEX files.But I am not really sure how to use Mex files either.
Thank you
Actually, MEX files allow you to include C code in Matlab programs, for example if you want to use external C libraries in Matlab.
What you want to do is use the Matlab Engine:
http://www.mathworks.com/help/techdoc/matlab_external/f29148.html
As an alternative, you could use linear algebra libraries that are written purely in C, such as LAPACK and BLAS. ( www.netlib.org )
you can use the matlab engine as Lagerbaer points out. However sometimes it can be convenient just calling the matlab process commandline style. I use this often when I don't want to mess with mxArrays etc, or when the amount of matlab code that needs executing gets really large. PseudoCode:
WriteArrayInMFormat( "in.m", myInputNumbers );
LaunchProcess( "matlab", "-nodesktop -r \"myFunction( 'in.m' )\" -logfile out.m" );
ReadArrayInMFormat( "out.m", myResult );
For me this is especially useful when testing things out: instead of having to recompile the C/C++ program each time I change something, I just apply all changes in the myFunction.m file. At that point I don't even need the C program, instead everything can be tested in matlab.

Resources