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

3 ビュー (過去 30 日間)
ren chongling
ren chongling 2021 年 6 月 3 日
回答済み: Abhiram 2025 年 6 月 10 日
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,

回答 (1 件)

Abhiram
Abhiram 2025 年 6 月 10 日
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!

カテゴリ

Help Center および File ExchangeSimulink Coder についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by