Understanding behavior of member functions loaded at runtime
Maeriden via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 17 16:35:08 PDT 2015
============================================================
module dll;
struct S
{
int a;
int b;
int method()
{
return a + b;
}
}
============================================================
module test;
import core.sys.posix.dlfcn;
import core.stdc.stdio;
import dll;
pragma(lib, "dl");
pragma(mangle, S.method.mangleof)
__gshared int function(S* self) paramMethod;
__gshared int function() noparamMethod;
void main(string[] args)
{
void* lib = dlopen("dll.so", RTLD_LAZY);
string funcName = S.method.mangleof;
noparamMethod = cast(typeof(noparamMethod)) dlsym(lib,
funcName.ptr);
paramMethod = cast(typeof(paramMethod)) dlsym(lib,
funcName.ptr);
int result = noparamMethod();
printf("%d\n", result);
S s = { 1, 1 };
result = paramMethod(&s);
printf("%d\n", result);
result = s.method(); // Symbol resolved because of pragma(mangle)
printf("%d\n", result);
// Error: function dll.S.method () is not callable using
argument types (S*)
//result = S.method(&s);
//printf("%d\n", result);
}
============================================================
dmd -fPIC -shared -defaultlib=libphobos2.so dll.d
dmd -defaultlib=libphobos2.so -L-rpath=. test.d
the output is
0
2
Segmentation fault
My questions are
1) Why does 'noparamMethod" return 0?
I assume that 'this' points to S.init but how does it know where
to find it? What's going on?
2) typeof(S.method) is "int()". Why's that? In C++ it would have
been "int(S* const)" and I though in D it would have been
"int(S*)"
2.1) Is this related to why case 4 doesn't compile?
3) Why does case 3 crash? I assume it's because there is no
argument so 'this' is null, but wouldn't the call be translated
to "S.method(&s)"?
More information about the Digitalmars-d-learn
mailing list