Search code examples
javajava-native-interfacejna

invoke c++ main method from java using jna


I am trying to invoke a c++ method from java using JNA on a mac/unix environment.

I have two questions.

  1. So far I could successfully implement simple examples but I am not sure how i could write a java counter part for the following C++ method:

    int main(int argc, char* argv[]){...}
    

Java code I tried

public interface CTest extends Library {
        int main(int argc, Pointer argv);
    }

Gives

java.lang.UnsatisfiedLinkError: Error looking up function 'main': dlsym(0x7fdee8c39300, main): symbol not found

Also tried the following

public interface CTest extends Library {
        int main(int argc, Object... argv[]);
        //doesnt work either - int main(int argc, String argv);
    }

To no avail. Same issue- symbol not found. Any tips? Ultimately I need to do something like this:

    CTest ctest = (CTest) Native.loadLibrary("ctest", CTest.class);
    String obj[] = new String[]{"-v, filepath/file"};
    ctest.main(2, obj);
  1. The second question is regarding implementing the above in a multi-threaded environment. I might have multiple libraries sitting in different locations so System.setProperty("jna.library.path",path-to-dylib) wont work. How can I achieve this?

Solution

  • Ok I figured this out myself, hoping for a quick answer but whatever. Here is the solution:

    Answer-1 : Below is my interface method.

        public interface CTest extends Library {
            public int main(int arc, String[] argv);
        }
    

    Answer-2: This is how I am planning to handle multithreading

        String argv[] = {"-v","path-to-file/file.extension"};
        System.load(this.getClass().getResource("libmylib.dylib").getFile());
        //load a different library later if required.. this way multiple threads load respective libs when/what they want
        HelloJNA.CTest ctest = (HelloJNA.CTest) Native.loadLibrary("mylib", HelloJNA.CTest.class);
    

    Hope this helps.