簡體   English   中英

如何在C中實現Java接口方法

[英]How to implement Java Interface methods in C

我們來看下面的代碼

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);
      }
    });
  }
}

我的問題是,我可以通過JNI在C / C ++中實現接口,而無需在Java中創建本機方法嗎?

一個選項是Java Native Access(JNA)庫。 看看JNA的項目頁面。 我引用其項目網站:

JNA為Java程序提供了對本機共享庫的輕松訪問,而無需編寫除Java代碼之外的任何內容 - 不需要JNI或本機代碼。 此功能可與Windows的Platform / Invoke和Python的ctypes相媲美。

項目的總結頁面中的以下示例演示了如何使用它從定義函數的本機庫中調用printf函數:

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]);
    }
}

}

在Windows上, printf函數在msvcrt.dll定義,示例加載該DLL並從中調用該函數。

JNA項目已經成熟,根據其網頁,它有一些非常着名的用戶。

應該指出的是,JNA本身使用了引擎蓋下的JNI,但在大多數情況下,您不需要自己使用JNI。 因此,您可以專注於在C中實現本機代碼(創建自己的DLL或共享庫文件),然后使用JNA在Java中加載它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM