[Durham] Calling C code from Java
martin at gkc.org.uk
Tue Sep 4 14:01:33 UTC 2012
On Wednesday 29 Aug 2012 at 23:57, Richard Mortimer <richm at oldelvet.org.uk>
> On 29/08/2012 22:31, Martin Ward wrote:
> > Are there any Java programmers out there that I can ask
> > a few questions about calling C functions from Java?
> I've done a small amount of calling C from Java.
> Feel free to ask questions here and I'll see if I know the answer.
I am looking into converting Assembler and COBOL code into Java:
for which there are two main problems:
(1) Data types: in assembler, any data can be used in any operation
regardless of type. In COBOL, all data is typed, but an area of memory
can be "redefined" as two or more different types (similar to C's union).
In Java, all data has a single type and cannot be recast or unioned.
The workaround for this is to determine the "main" type for each data item,
and declare it as that type, then develop conversion functions
for when the program wants to apply a different operation on a type
(eg convert a number to a string of bytes, or vice-versa).
(2) Pointers: specifically pointer arithmetic. Java only has a limited
form of pointers (references) with no pointer arithmetic or way to get
the address of a data item, or convert a number to an address.
The workaround here would be to pass a reference to the data to
a C function which returns an integer. The integer being simply
the address that the function was passed. Dereferencing a pointer
stored in an integer would word in the same way: pass an integer
to a C function which returns a pointer to the data (with the pointer
being simply the integer which was passed).
One problem here is that Java may not lay out data in memory
in an exact sequence: for assembler to C conversion we had
to put all the data into one large struct which was defined as packed.
This ensured that an offset from the address of one data item
would pick up the right data. In Java this may be more difficult.
Another problem is garbage collection: the Java garbage collector
might move data around and invalidate all the "fake pointers".
We might have to define any data we want to take the address of
on the "C side" of the boundary.
STRL Reader in Software Engineering and Royal Society Industry Fellow
martin at gkc.org.uk http://www.cse.dmu.ac.uk/~mward/ Erdos number: 4
G.K.Chesterton web site: http://www.cse.dmu.ac.uk/~mward/gkc/
Mirrors: http://www.gkc.org.uk and http://www.gkc.org.uk/gkc
More information about the Durham