vesii
vesii

Reputation: 3128

A few questions about loading libraries and native methods in Java

Part of my tries to understand why my code is hanging when running in different OS, I had to debug different eclipse plugins. I saw the following code in some Java file:

Library.loadLibrary("swt")

Based on What are native methods in Java and where should they be used?, I understand that native methods are used to execute functions written in different programming languages. But I have two question regarding it:

  1. When loadLibrary is called with the input "swt", what actually happens? Where loadLibrary looks for SWT library and how can I change it? What is the equivalent command in Linux to get the library (I guess it's some shared library)?
  2. Consider the following code:
    public static final native void _gtk_widget_destroy(long /*int*/ widget);
    public static final void gtk_widget_destroy(long /*int*/ widget) {
        lock.lock();
        try {
            _gtk_widget_destroy(widget);
        } finally {
            lock.unlock();
        }
   }

The _gtk_widget_destroy method is native. Does it mean that there is a method in another language (probably C) that is called _gtk_widget_destroy? How do I know from which library this method is coming from (maybe SWT)?

Upvotes: 1

Views: 236

Answers (1)

Botje
Botje

Reputation: 30830

System.loadLibrary("X") uses System#mapLibraryName to construct the actual library name. On Linux this is libX.so, on Mac it would be libX.dylib, and on Windows it is libX.dll.

It then searches for a library with that name in each entry of java.library.path (a VM property).

For your second question: you need the full namespace and class name of the surrounding class as well. A quick search tells me the full name of that method is org.eclipse.swt.internal.gtk.GTK#_gtk_widget_destroy. Now, there are two options:

  • Either libswt.so calls RegisterNatives to bind this method to a function pointer (typically in its JNI_OnLoad method.) This is not the case.
  • It uses the common name mangling scheme, which would result in a symbol with the name Java__org_eclipse_swt_internal_gtk_GTK_1gtk_1widget_1destroy. It seems the developers have abstracted that long name into a macro. You can use the standard nm tool to determine whether a given .so file contains that symbol.

Upvotes: 1

Related Questions