Shared library extern (C) variables

Jeremy DeHaan dehaan.jeremiah at gmail.com
Sun Jan 5 13:00:47 PST 2014


On Sunday, 5 January 2014 at 19:55:50 UTC, Mineko wrote:
> On Sunday, 5 January 2014 at 19:47:46 UTC, FreeSlave wrote:
>>
>> Some code snippets of what you try to do would help.
>>
>> Maybe this example explain you something:
>>
>> //mod.d
>> extern(C) int foo = 42;
>>
>> void changeFoo(int val)
>> {
>>    foo = val;
>> }
>>
>> //main.d
>> import std.stdio;
>> import mod;
>>
>> int main()
>> {
>>    writeln(foo);
>>    changeFoo(15);
>>    writeln(foo);
>>    return 0;
>> }
>>
>> Compile:
>> dmd -H -c mod.d && //to generate .di file (not required)
>> dmd -shared mod.d -oflibmod.so && //to generate shared library
>> dmd -L-L. -L-lmod -L-rpath=. main.d //rpath is special 
>> argument to linker, so executable will able to find shared 
>> library in its directory. You can omit rpath, but then you 
>> must put your .so file to one of standard directory like 
>> /usr/lib or /usr/local/lib. That's all for Linux. On Windows 
>> you would have different building steps.
>>
>> Also probably you want to make your varialbe __gshared, so it 
>> will not be thread-local. That's default D behavior to make 
>> all global variables thread-local. And I don't know how other 
>> languages will handle D thread-local variable.
>
> Ahh I appreciate it, but I already have that part down and 
> good. :)
>
> I was wondering about how to use export correctly, I apologize 
> for not being clear.
>
> Also I'll keep in mind the __gshared, never even knew about it.

Yeah, the documentation could definitely be better in this 
regard. I don't really have any experience when it comes to 
linking to D shared libraries. All my experience comes from 
linking with C ones.

I might try it out later today just to make sure I have it right, 
but it should be something kind of like this:


libstuff.d

//extern(C) only added because that is what you have been doing
export extern(C) void someFunction(int thing)
{
     //doing stuff with the thing
}

extern(C) void otherFunction(int otherThing)
{
      //stuff with a different thing
}

Assuming libstuff gets put into the shared library


main.d


import libstuff;


void main(sring[] args)
{
      int sweetVariable = 100;
      someFunction(sweetVariable);//should be ok
      otherFunction(sweetVariable);//error, not exported
}


Again, I cannot confirm that this is the exact way to do it, but 
it should be something very similar from what the documentation 
leads me to believe.


More information about the Digitalmars-d-learn mailing list