mercredi 5 septembre 2018

Simulink "Access Violation" writing to PWork variable in capture list of C++ lambda function

I have a C++ S-Function that handles a set of threaded operations through std::thread, std::async and callbacks. The thing is that one of the callbacks is an S-function that has a buffer in the capture list. This buffer is in the PWork of the Simulink model. However, it seems that Matlab crashes as soon as I try to write to it.

Below is a minimal crashing example of my S-Function (only the mdlStart function), which contains the relevant code:

static void mdlStart(SimStruct *S)
{
    ssGetPWork(S)[0] = (void *) new ThreadedDataServer();
    ssGetPWork(S)[1] = (void *) new DatagramAssembler();
    ssGetPWork(S)[2] = (void *) new MyBufferType(); // actually an std::array<char, LARGENUMBER>

    auto server          = (ThreadedDataServer *) ssGetPWork(S)[0];
    auto assembler       = (DatagramAssembler*)   ssGetPWork(S)[1];
    auto copy_buffer_ptr = (MyBufferType *)       ssGetPWork(S)[2];

    server->attachDataHandler([&copy_buffer_ptr, &assembler](const ThreadedDataServer::buffer_t & buffer, size_t num_bytes)
    {
        /* Minimal crashing action */
        copy_buffer_ptr->at(5) = 'b'; // Any index != 0
        /* Original code */
        //std::copy(buffer.begin(), buffer.begin() + num_bytes, copy_buffer_ptr->data());
        //assembler->feedData(*copy_buffer_ptr, num_bytes);
    });
}

The handler is invoked from the data server worker thread (different from Simulink main thread). Other actions inside the callback function work smoothly (reading parameters, doing other operations...).

Any hint why this happens? The same code was working in an independent executeble before integrating it in Simulink.

Aucun commentaire:

Enregistrer un commentaire