Calling C functions

Steven Schveighoffer schveiguy at yahoo.com
Thu Dec 9 08:52:24 PST 2010


On Thu, 09 Dec 2010 11:38:00 -0500, Andrej Mitrovic  
<andrej.mitrovich at gmail.com> wrote:

> I know I prefer using shared() when interfacing with C.
>
> I've tried using __gshared once when interfacing with C code. But I
> had crashes all the time, using shared instead made my app stable
> again. It might be related to the way the C code worked, since
> multiple threads were involved. Anyway.. that's my experience with
> gshared..

__gshared is the equivalent of what normal globals used to be (in D1 and  
earlier versions of D2).  It's the same as a global variable in C.

shared is exactly the same as __gshared except the compiler inserts memory  
barriers around reads/writes (the C compiler does not), and shared is a  
type modifier, so it's available in the TypeInfo of the variable.  Some  
parts of the runtime use that to determine certain behaviors, and I am  
aware of one problem with __gshared that needs to be documented -- array  
appending.

__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?

BTW, __gshared should have no problems in a single-threadded app.

-Steve

> On 12/9/10, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
>> On Thu, 09 Dec 2010 10:15:59 -0500, CrypticMetaphor
>> <CrypticMetaphor88 at gmail.com> wrote:
>>> And how I supposed to call the c function?
>>
>> Mark the extern(C) integer as __gshared in D.  That will put it in the
>> global namespace instead of TLS.
>>
>> e.g.:
>>
>> extern(C) { // this is needed to make it available from C
>>    __gshared int globalFromD;
>> }


More information about the Digitalmars-d-learn mailing list