1

I am trying to wrap a C library using JNI.

I am interested about the prospects of using any C library using JNI (particularly with Android, but I assumed this compatability should be the same as being compatible with JNI).

Without being an original developer of a C library, I've found it confusing to know, what methods I need to register in JNI_OnLoad (https://developer.android.com/training/articles/perf-jni#native-libraries).

To progress, I figured out with the help of https://stackoverflow.com/a/4514781/4959635 to call

nm myclib.a | grep " T "

to find a list of (supposed) "exported functions". However, the nm output may well tell other things as well.

Now my question is,

will the library work, if I wrap only the exported functions via JNI_OnLoad?

Or do I need to ensure other qualities in the library in order to guarantee that it will work with JNI?


On the other hand, I read some other discussions such as:

https://www.thecodingforums.com/threads/unsatisfiedlinkerror-when-loading-shared-lib.360242/

which suggested that having undefined symbols might mean that the C code is not structured properly for JNI.

Whereas this resource:

https://www.baeldung.com/jni

seems to suggest that wrapping exported functions is in fact what's expected.

mavavilj
  • 121
  • 13

1 Answers1

0

No. Functions you call from JNI must always follow a specific signature: (ignoring the return type for now)

fun(JNIEnv *env, jobject obj, ...)

or

fun(JNIEnv *env, jclass cls, ...)

where the remaining arguments are types that the JVM can process.

You will need to create wrapper functions that go between the JVM types and whatever types your functions expect. See the SWIG library for a potential means of auto-generating these wrappers, but know you will still need to write quite a bit of custom code.

Botje
  • 21,384
  • 3
  • 27
  • 38
  • This reinforces the idea that JNI is a painful idea for using C libraries, since it seems to require so much extra work. Is it possible to look for C libraries that are particularly easy to wrap then? A particular further interest is the time spent on writing wrapper code (and understanding how to do it for a particular library) vs a Java implementation. – mavavilj May 13 '22 at 12:16
  • "[looking] for C libraries that are particularly easy to wrap" is putting the horse before the cart, I would say. If your real question is "what makes an API easy or hard to integrate with JNI", I would say excessive use of pointer arguments and custom classes. Take a look at the SWIG and JNA projects for some assistance in using native libraries. – Botje May 13 '22 at 17:52