crash di matlab in una S funcion con un riferimento ad un std::mutex

1 view (last 30 days)
Ho costruito una S Function scritta con codice C/Cpp che contiente un std::mutex ma purtroppo all'esecuzione della simulazione matlab crasha, se genero codice C di tutto il modello (compresa l'S function funziona tutto), In questo micro codice di esempio è stato rimosso tutto tranne la funzione che genera il crash: mutex_buffer.lock();
Il codice dell'S Funcion è il seguente:
UDPtoSTRUCT.cpp
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <mutex>
#include "MyParams.h"
MyParams params;
std::mutex mutex_buffer;
MyParams ReceiveMyParamsMatlab(int8_t* ErrorCode, const uint8_t* ip_addr, const uint16_t* port) {
mutex_buffer.lock();
params.param1 = 1;
params.param1 = 2;
mutex_buffer.unlock();
return params;
}
MyParams.h
#ifndef MY_PARAMS
#define MY_PARAMS
struct MyParams {
float param1;
float param2;
} ;
#endif
Qui la funzione per generare il codice: CreateSFunction.m
% Define the S-Function information
def = legacy_code('initialize');
Simulink.importExternalCTypes('MyParams.h');
% Specify the function prototype and file details
def.SFunctionName = 'UDP_to_STRUCT_Sfun'; % Name of the generated S-Function
def.OutputFcnSpec = 'MyParams y1 = ReceiveMyParamsMatlab( int8 y2[1], uint8 u1[16], uint16 u2[1])'; % Function signature
def.SourceFiles = {'UDPtoSTRUCT.cpp' }; % Source file(s)
def.HeaderFiles = {'udpSTRUCT.h'}; % Header file(s) if required
def.IncPaths = {'./'}; % Path to header files (optional)
def.SrcPaths = {'./'}; % Path to source files (optional)
def.Options.language = 'C++';
% Generate the S-Function
legacy_code('sfcn_cmex_generate', def);
% legacy_code('compile', def);
legacy_code('sfcn_tlc_generate', def);
% Compile the S-Function
legacy_code('compile', def);
% Now you can use 'my_function_sfunc' in Simulink
disp('S-Function generated and compiled successfully.');
qui l'immagine del modello matlab che crasha in simulazione:
Sono definite due costanti e 2 display collegati alla SFunction
Per la generazione di codice viene usato Visual Studio 2022

Answers (1)

Harsh
Harsh on 7 May 2025
Hi @Mauro,
I tried to reproduce the issue at my end but it looks like a few files have not been provided.
Since "std::mutex" is used to lock and unlock resources, it’s possible that the crash only happens on certain machines, depending on how resources are managed. To figure out what’s causing the crash, try debugging the S-function directly on your machine. This can help you pinpoint exactly where and why the problem occurs.
For step-by-step guidance on debugging C-MEX S-functions, check out the MathWorks documentation:
I hope this helps, thanks!

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!