I've resorted to using chdir as @technomage (I can't seem to upvote his/her comment with my current account status) has also suggested.
To do this, I used the following piece of code before I load up my C++ DLL through JNA.
NativeLibrary clib = NativeLibrary.getInstance(null);
int result = clib.getFunction("_chdir").invokeInt(new Object[]{"<PATH GOES HERE>"});
Source: https://www.java.net/node/643965#comment-821128
You can also check the result by checking the result
variable. Should be zero if everything went well.
I am not quite sure why null
works for NativeLibrary.getInstance
. The documentation doesn't say anything specifically about this and I haven't been able to glean anything from the source here: https://github.com/twall/jna/blob/master/src/com/sun/jna/NativeLibrary.java - But passing null does seem to get you the default libc or equivalent for your platform.
Note also that I had to add an _
(underscore) to the function name. This has to do with how function calls get mangled when compiled on Windows. As far as I know, this isn't required on other platforms, but I don't have the ability to test this right now.
Since I was unsure about whether my call was actually working, I did the following first:
Function f = clib.getFunction("_chdir");
This returns a function "pointer" f
that you can trace/debug to see if you have a valid reference. Luckily, in my case, all I had to do was add the underscore as was suggested in the source link above.
After this call to chdir
, the C++ DLL I need to access has been happily accessing files relative to the location specified in chdir
.