C code not working inside MATLAB System

1 vue (au cours des 30 derniers jours)
Carlo Savorgnan
Carlo Savorgnan le 12 Avr 2016
Commenté : Ryan Livingston le 12 Avr 2016
I'm trying to interface some C code inside a MATLAB system derived class. The C function I want to use multiplies by 3 the input argument. File "triple.h":
#ifndef __TRIPLE_H__
#define __TRIPLE_H__
#ifdef MATLAB_MEX_FILE
#include <tmwtypes.h>
#else
#include "rtwtypes.h"
#endif
double triple(double in);
#endif
File "triple.c":
#include "triple.h"
double triple(double in)
{
return in*3;
}
I defined a MATLAB function "call_triple" so that I can call the C function. File "call_triple.m":
function out = call_triple(in)
%#codegen
assert(isa(in, 'double'));
if coder.target('MATLAB')
out = call_triple_mex(in);
else
out = double(0.0);
out = coder.ceval('triple', in);
end
I compiled with the MATLAB coder "call_triple" to obtain "call_triple_mex":
>> codegen -config:mex call_triple triple.h triple.c
Now I can use call_triple from MATLAB command line:
>> call_triple(2.4)
ans =
7.2000
Finally I implemented the class "triple_system"
classdef triple_system < matlab.System & coder.ExternalDependency
...
... more code
...
function out = stepImpl(~, in)
out = call_triple(in);
end
...
... more code
...
The class works from the command line:
>> obj = triple_system;
>> step(obj, 3.2)
ans =
9.6000
The problem arises when I use the class inside a "Matlab system" block inside Simulink and I select the option "Simulate using: code generation". The output of the Simulink block returns a number which makes no sense to me (like 1689233153 or similar big numbers). The block works fine when I select: "Simulate using: interpreted execution".
What am I doing wrong? I wold expect the same behaviour from the two simulation methods.
Thanks
Carlo

Réponse acceptée

Ryan Livingston
Ryan Livingston le 12 Avr 2016
You likely need to add coder.cinclude('triple.h') in the System Object to include the header for triple. Without the declaration of triple, the C compiler assumes that the signature is int triple(int) which results in the unexpected behavior that you are seeing.
  2 commentaires
Carlo Savorgnan
Carlo Savorgnan le 12 Avr 2016
I added coder.cinclude('triple.h') inside the definition of call_triple and now it works.
Thank you!
Ryan Livingston
Ryan Livingston le 12 Avr 2016
Glad to hear it, that's a hard error to track down.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Simulink Coder dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by