Skip to main content

Adding native C Code to Squawk

3 replies [Last post]
Joined: 2011-07-26

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2006-09-08

[My earlier reply seems to have vanished, so here's a shorted version:]

The best bet would be to use JNA. There are basic examples in the javadoc (see

You can also look at the code in and com.sun.squawk.platfrom.window.natives. The posix version is more functional, but the factoring makes it harder to see the overall picture.

Joined: 2006-09-08

JNA would be the best approach for this. Some basic examples are in the javadoc:

The basic steps are:

  • Compile and link your C code as a shared library
  • Create a Java wrapper class for that library
  • Look up the shared library at runtime using the NativeLibrary.findInstance()
  • Create Function pointers to the C functions
  • Create methods that call the C functions using the Function pointer.
  • Create structures and constants as needed.

There are more complicated examples in the CLDC code. Look at and The posix code is harder to follow due to the factoring, but is a complete implementation.

Joined: 2011-08-08

derek_white wrote:

JNA would be the best approach for this. Some basic examples are in the javadoc:

[my reply yesterday appears to be lost, too... hmm... trying again...]

True that JNA is probably the easiest way, but for deployment complexity one does not want to bundle an additional .so and care about potential platform dynamic linker issues.

So, to make things "just work" one links the C code statically to the Squawk binary. Easy. Then Java needs some wrapper method definitions to refer to, ok. But, intuitively, at some point when jumping to a new method the VM must decide whether it lives in Java land or whether this is a C native function.

So, how to mark methods to be a C native implementation?
How to map Java method names to C native names?
Where does one put the translation table from method names to C function
Of course, the C code has to unwrap passed arguments as they are
stored how the VM likes them.

Can anyone point to a simple example of calling a statically linked portion of C code, passing in and out some data - or where does this magic happen in Squawk?