Search code examples
javaxcodemacosjnadylib

MAC OSX-Write Xcode .Dylib to use in JNA (Java Native Access ) -JAVA


Till now i was using dll file with JNA in windows successfully. I had created dll in VC++ successfully which then loaded in Java using JNA. But now i have requirement where i need to provide same software in Mac Os also.

as I have not worked with mac os and Xcode i don't know how to create .dylib.

Here is what i have tried so far using Google and other resources.

1)Opened Xcode, selected "create a new Xcode project"

2)Selected Framework & library , and clicked C/C++ Library

3)I gave Project Name as SimpleDylib and choose Type as Dynamic and pressed next.

4)then i added new file, a C++ file to this project and gave name as SimpleDylib.cpp

5) I wrote a simple function

int addNumber(int a,int b) { return a+b; }

From here i don't know how to export this function. Like in windows VC++ i use .def file to export the function successfully. And in java using jna i am able to use this dll and function inside dll successfully.

in Xcode i tried to use

#define EXPORT _attribute__((visibility("default"))) EXPORT int addNumber(int a,int b) { return a+b; }

but still i was not able to use this dylib in Java and i get error as

Exception in thread "main" java.lang.UnsatisfiedLinkeError: Error lloking up function 'addNumber' : dlsym(0x7fb930d49930,addNumber) : symbol not found

So how do i export function from dylib? Did my above steps are correct so far? What is the way to create .dylib which can be loaded and use in JNA-JAVA.


Solution

  • If your file is a .cpp file then you're undoubtably suffering from C++ name mangling.

    You need to add extern "C" to the export like:

    extern "C" EXPORT int addNumber(int a,int b)
    

    To verify if the routine is mangled or not, you can look at the .dylib using nm, a mangled version of the routine would look like: __Z9addNumberii while an unmangled version would look like _addNumber.

    Additionally, on OSX, the preferred extension for shared libraries that are used with JNI/JNA are .jnilib, not .dylib, but they're identical in all but file extension