Thread overview
shared library, function arguments order reversed?
May 21
xoxo
May 21
kinke
4 days ago
xoxo
May 21

Hello, I am loading a library built with dmd on linux, but when I call other functions, the arguments order is reversed

I understand calling convention from C/D is different, but shouldn't the compiler handle that automatically? if not, then that sounds like a bug?

LD_LIBRARY_PATH="."

dmd -of=mylib.so -shared -betterC -fPIC -version=DLL app.d
dmd -of=app -betterC -fPIC app.d && ./app
import core.stdc.stdio;
import core.sys.posix.dlfcn;

extern(C) void main()
{
    // load library and symbols
    auto lib = dlopen("mylib.so", RTLD_NOW | RTLD_DEEPBIND);
    auto fn_test = cast(void function(int, int)) dlsym(lib, "test");

    assert(lib);
    assert(fn_test);

    int a = 1;
    int b = 2;

    tick(a,b); // prints 1 2  ✅

    // call the loaded symbol, it'll then call `tick`
    fn_test(a,b); // prints 2 1 ❌
}

void tick(int a, int b)
{
    printf("%d %d\n", a, b);
}

version (DLL)
extern(C) export
void test(int a, int b)
{
    tick(a, b);
}

Thanks

May 21

On Wednesday, 21 May 2025 at 08:09:23 UTC, xoxo wrote:

>

auto fn_test = cast(void function(int, int)) dlsym(lib, "test");

This is the problem - you're casting the address to an extern(D) function pointer. Use something like this:

alias Fn = extern(C) void function(int, int);
auto fn_test = cast(Fn) dlsym(lib, "test");
4 days ago

On Wednesday, 21 May 2025 at 10:43:17 UTC, kinke wrote:

>

On Wednesday, 21 May 2025 at 08:09:23 UTC, xoxo wrote:

>

auto fn_test = cast(void function(int, int)) dlsym(lib, "test");

This is the problem - you're casting the address to an extern(D) function pointer. Use something like this:

alias Fn = extern(C) void function(int, int);
auto fn_test = cast(Fn) dlsym(lib, "test");

Thanks, it now works, I didn't know we could set it that way