How to export a swift function to shared object that can be used by dlsym on Linux?

My main.swift has a function

@_cdecl("my_add") // export to C as intptr_t my_add(intptr_t, intptr_t);
public func add(x: Int, y: Int) -> Int {
  return x + y
}

I compiled main.swift to main.so and then used for this C code:

#include <dlfcn.h>
#include <stdio.h>

int main() {
        void *b = dlopen("./main.so", RTLD_NOW);
        void *c = dlsym(b, "my_add");
        printf("%p\n", c);
        printf("%s\n", dlerror());
}

The result was:

(nil)
./main.so: undefined symbol: my_add

I used readelf to check my_add function

$ readelf -s main.so | grep my_add
31024: 00000000000525c0    15 FUNC    GLOBAL PROTECTED   12 my_add

How can I export my_add function to use by C code?

I need the help :frowning:

I have no idea how to solve this but it looks like a really cool question! :grinning:

Is there a way to check the pointer is being parsed correctly, with GDB for instance to see if b is NULL?

Terms of Service

Privacy Policy

Cookie Policy