简体   繁体   中英

How to implement Java Interface methods in C

Let's take the following code

public class SomeClass {

  public OtherClass method(final String param1,final String param2){
    AnotherClass obj1 = AnotherClass.getInstance();
    return obj.instanceMethod(new YetAnotherClass<OtherClass>() {
      @Override
      public OtherClass run() {
        return OtherClass.get(param1, param2);
      }
    });
  }
}

My question is there any way that I can implement the interface in C/C++ through JNI, without creating a native method in Java?

One option is the Java Native Access (JNA) library. Have a look at its project page at JNA . I quote from its project site:

JNA provides Java programs easy access to native shared libraries without writing anything but Java code - no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes.

The following example from the project's toturial page demonstrates how it is used to call the printf function from the native library that the function is defined in:

package com.sun.jna.examples;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

 /** Simple example of JNA interface mapping and usage. */
public class HelloWorld {

// This is the standard, stable way of mapping, which supports extensive
// customization and mapping of Java to native types.

public interface CLibrary extends Library {
    CLibrary INSTANCE = (CLibrary)
        Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
                           CLibrary.class);

    void printf(String format, Object... args);
}

public static void main(String[] args) {
    CLibrary.INSTANCE.printf("Hello, World\n");
    for (int i=0;i < args.length;i++) {
        CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
    }
}

}

On Windows, the printf function is defined in the msvcrt.dll and the sample loads that DLL and calls the function from it.

The JNA project is mature and according to its web page, it has some very famous users.

It should be pointed out that JNA itself uses the JNI under the hood but in most cases, you do not need to use JNI yourself. Therefore, you can focus on implementing your native code in C (create your own DLL or Shared Library files) and then load them in Java with JNA.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM