How to use Simulink generate C++ code which include C++ std:: function ,for example lower_bound function

3 visualizzazioni (ultimi 30 giorni)
Hello guy ,I have a question , how to use simulink generate C++ Std:: function . For example, I just want lower_bound(C++ <algorithm>function) function in generation C++ code. I use matlab function , also use #include<algorithm> ,but it dosenot work,

Risposte (1)

Abhiram
Abhiram il 10 Giu 2025
To use C++ standard library functions such as “lower_bound” in Simulink and use the model to generate C++ code, you will need to wrap the standard function inside a custom user-defined C++ function. A sample implementation is given:
// lower_bound_wrapper.cpp
#include <algorithm>
extern "C" int lower_bound_wrapper(const double* arr, int size, double value) {
const double* it = std::lower_bound(arr, arr + size, value);
return static_cast<int>(it - arr);
}
// lower_bound_wrapper.h
#ifndef LOWER_BOUND_WRAPPER_H
#define LOWER_BOUND_WRAPPER_H
#ifdef __cplusplus
extern "C" {
#endif
int lower_bound_wrapper(const double* arr, int size, double value);
#ifdef __cplusplus
}
#endif
#endif
The C++ function can be called in Simulink by using the C Caller Block (from User-Defined Functions library) and configuring the C Caller block appropriately.
The final step is to configure code generation for C++ by following the given steps:
  • Go to Model Settings
  • Under Code Generation > Language – set language to C++
  • Under Code Generation > Custom Code:
  • In Include headers – add the “lower_bound_wrapper.h” file
  • In Source files – add the “lower_bound_wrapper.cpp” file
  • Go to Apps > Embedded Coder (if available) or use Simulink Coder
  • Click Build
Hope this helps!

Categorie

Scopri di più su Simulink Coder in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by