Search code examples
javaandroidcjava-native-interfacejna

JNA passing the equivalent of swift pointer from Java Android to C


I am a little stuck trying to pass an implementation of this Swift code in Java, to C. Would appreciate any advice i am using JNA to integrate between the Java and Matlab generated C code.

This is the Swift call:

GetResult(uptime, &result_out)

It Maps to the C code:

void GetResult(double time, Result_t *Result)

The C struct Result_t is too big for here, however it is a combination of double's and int's.

I understand &result_out is a swift pointer? How is it best to go about implementing the equivalent of the Swift pointer in Java and then be able to pass it to C that is expecting a pointer to the Result_t which as i mentioned is a structure made up of doubles and ints.


Solution

  • The & denotes the memory address of a variable. In this case, it means the memory address of the Result structure.

    In C you can see the * symbol used to denote the same thing: the variable to be passed as the second argument is the reference/memory address of the underlying data.

    These often appear in pairs: if you have a variable foo defined you can easily pass &foo to any method expecting the pointer to foo, while the method itself uses the * notation to let you know it requires that pointer.

    For many JNA structures you need to pay close attention to these symbols. Knowing whether to pass an int or IntByReference, for example, is key. But fortunately (for ease of writing code, or unfortunately for consistency) the behavior of the JNA Structure class is different. The bottom line is that, by default, when a Structure is included as an argument to a method/function (the most common application) the pointer, or ByReference version of the structure is used. So in this particular case, assuming you have mapped a class Result extends Structure with all the information, you can simply pass result where result = new Result();.

    There are ways to use ByReference and ByValue to override this default behavior but that's beyond the scope of your question.