Please take a minute to review and accept our Terms of Use.
Welcome to the PLECS User Forum, where you can ask questions and receive answers from other members of the community.

Many technical questions regarding PLECS are answered on the Technical Solutions page of our website. Tutorial videos, specific application examples, and pre-recorded webinars are available on our YouTube page. Please follow us on LinkedIn for the latest Plexim news.

How to write DLL to make it reentrant?

0 votes

I try to write reentrant DLL based on example pi_controller project. I need to use one dll several times in a one simulation model simultaneously. I introduced struct "Converter_struct" and try to put there all variables. I used malloc to allocate memory for the struct. The struct pointer is assinged to aState->userData. After lauching simulation, it does not work. Structure variables are 0 or has random values.

asked Sep 26, 2022 by mikkki (12 points)
edited Sep 27, 2022 by mikkki

1 Answer

+1 vote

A reentrant DLL must not use global variables. You are using the global variable C.

If your model contains two instances of your DLL, i1 and i2, the DLL is only loaded once. Therefore, there is only one instance of C.

You allocate memory to a Converter_struct for both instances i1 and i2 in plecsStart(). Now, as soon as the simulation starts, plecsStart() will be called for both instances i1 and i2 - but you cannot make any assumption for which instance it is called first. In any case, C will only point to the memory allocated in the last call to plecsStart().

During the simulation, plecsOutput() is called for both instances i1 and i2. Again, you can make no assumptions about which instance is called when. Since you use the global variable C directly, you will always work with the memory allocated in the last call to plecsStart(), regardless whether plecsOutput() is called for i1 or i2.

The solution is simple: Get rid of the global variable C. Instead, use a local variable declaration in both plecsStart() and plecsOutput(). In plecsOutput(), assign your local variable to the value of aState->userData, which you already used in plecsStart() to store a pointer to the memory that you allocated for C.

answered Oct 3, 2022 by Oliver Schwartz (626 points)