Calling C functions

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Dec 9 09:24:05 PST 2010


On 12/9/10, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
> __gshared is unprotected sharing, and the type system is not aware that it
> is shared.  Can you remember what specifically you were doing with the
> variable?

My dev PC is in repairs right now so I don't have the code atm. It's a
project that works with audio devices and does some basic processing
on audio data.

But from what I can recall I would pass my D callback function to C,
which would call the callback with an interrupt or very-high level
priority thread (it depends on the device driver implementation) at
many intervals per second. The D callback would do some processing,
update one structure variable (e.g. struct "status"), and return.
Inside main() I had an infinite loop which would wait for the device
driver to stop calling the callback. One way of knowing if the device
driver stopped is to check a flag inside the struct, e.g. a boolean
status.done.

The problem I was having at first was that the status struct inside
the callback was a new TLS variable, and the one main() was seeing was
a distinct variable. So main() would never see the updated struct.
I've tried marking the struct with __gshared, but this would
immediately crash my application. Using shared() instead fixed this
problem. This was using DMD 2.048 and I haven't tried newer versions
yet.

Of course, there are much better ways of notifying when the device
driver is done instead of polling the status.done flag all the time.
For example, with PortAudio (an audio library) I can use message
passing to notify my foreground thread that the background (working)
thread is done, or that the device driver has suddenly stopped
working. I could do the same with my first project, but PortAudio is a
mature and stable library so I've decided not to deal with device
drivers directly in my D code (otherwise I would have to write code
for all the audio device driver standards -- ASIO, WDM, CoreAudio, etc
etc..).


More information about the Digitalmars-d-learn mailing list