Use c Code in Matlab and deal with pointers

5 views (last 30 days)
Lars Hagemann
Lars Hagemann on 8 Nov 2018
Edited: Guillaume on 8 Nov 2018
My goal is to integrate my allready written C-Code in Matlab. For this purpose I have written an example code to explain my problem.
First I´m building a mex file and then call the function callfooadd_mex.
a=2;
b = 3;
build_mex mex;
[a,b] = callfooadd_mex(a, b);
disp(a);
disp(b);
The function callfooadd uses coder.ceval to call the C-Code.
function [var_1, var_2] = callfooadd (var_1,var_2) %#codegen
y = 0.0;
z = 0.0;
coder.updateBuildInfo('addSourceFiles','addieren.c');
coder.cinclude('addieren.h');
coder.ceval('addieren', coder.wref(var_1), coder.wref(var_2));
end
C-Code:
% code
#include <stdio.h>
#include <stdlib.h>
#include "addieren.h"
void addieren( double* in1, double* in2)
{
*in1 = *in1+1;
*in2 = *in2+1;
}
This way works great but I would like to renounce the return values of callfooadd() while a and b are still added with one in the first script. Is there a way that permits this?

Answers (1)

Guillaume
Guillaume on 8 Nov 2018
Edited: Guillaume on 8 Nov 2018
I know nothing about coder but I don't understand why you're structured your current code the way it is. From the C-code point of view, the first two parameters are unused (I'd expect you get a warning when compiling) and in any case have no link to the pointer parameters. Why isn't the function signature simply:
void addieren(double* in1, double* in2)
With regards to I would like to renounce the return values of callfooadd()", in theory at the mex level you can do in-place modification of matlab variables but I don't know if coder will let you do that. However, this would be extremely dangerous and fragile and would easily break m code since matlab won't know nor expect that you've done in-place modification. This will inevitable break m code.
  2 Comments
Lars Hagemann
Lars Hagemann on 8 Nov 2018
thanks for the quick reply. var1 and var2 are useless in the c function but I got some error messages in the build file if I dont include them. So there is no safe way to include c code in Matlab and work with pointers without changing the C-Code?
Guillaume
Guillaume on 8 Nov 2018
Edited: Guillaume on 8 Nov 2018
Matlab paradigm is fundamentaly different from C. Everything is based on the fact that arguments are passed by values. Passing arguments by reference is not supported (except for handle classes).
You will have a better coding experience in matlab if you forget the C mindset and switch to matlab's mindset. Yes, some things are not as efficient, you can't do in-place modification (although in some instances matlab's JIT will detect that it can be done and actually modify the original variable instead of creating a copy) but others are much simpler: e.g. vectorised code replaces C for loops.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!