I read how to load functions from a static library from this answer: https://stackoverflow.com/a/10366323/6123767
But I need to load a class from the static library, not just a function, how can I achieve it?
classes are not actually a thing in exported binaries. They are just a fancy struct basically. And structs are basically just the layout of memory with data. Libraries mostly only contain functions.
So what you actually want to do is creating a class containing the member function declarations and adding the member variables in it like this:
library/somelib.d:
module somelib;
class Foo
{
private long member;
this(long n)
{
member = n * 2;
}
int func(int x)
{
return cast(int) (x + member);
}
}
wrapper/somelib.d:
module somelib; // module names need to match!
class Foo
{
private long member;
this(long n);
int func(int x);
}
app.d:
module app;
import std.stdio;
import somelib;
void main()
{
Foo foo = new Foo(4);
writeln("foo: ", foo);
writeln("func: ", foo.func(5));
}
Compile library with dmd -lib library/somelib.d -ofsomelib.a
(or .lib on windows)
Compile executable with dmd app.d -Iwrapper somelib.a -ofapp
(or .lib/.exe on windows)
I did -Iwrapper
instead of specifying the filename so the module names can match the file/folder paths because the module name of wrapper/somelib.d must match the module name of library/somelib.d because thats how function names are mangled in D.