阅读量:104
要在Java中调用C#方法并传递参数,你可以使用Java Native Interface (JNI) 和 Java Native Access (JNA) 库。这里我将向你展示如何使用这两种方法。
方法1:使用JNI
- 首先,创建一个C#类并导出需要调用的方法:
using System;
public class MyClass
{
[DllImport("Kernel32.dll")]
public static extern int Add(int a, int b);
}
- 然后,使用Java的
javah工具生成JNI头文件:
javah -jni MyClass
- 创建一个Java类,实现生成的JNI头文件中的本地方法:
public class MyClassWrapper {
static {
System.loadLibrary("myclass");
}
public native int add(int a, int b);
public static void main(String[] args) {
MyClassWrapper myClassWrapper = new MyClassWrapper();
int result = myClassWrapper.add(3, 4);
System.out.println("Result: " + result);
}
}
- 编译并运行Java程序:
javac MyClassWrapper.java
java MyClassWrapper
方法2:使用JNA
- 首先,创建一个C#类并导出需要调用的方法:
using System;
using System.Runtime.InteropServices;
public class MyClass
{
[DllImport("Kernel32.dll")]
public static extern int Add(int a, int b);
}
- 创建一个Java类,使用JNA库调用C#方法:
import com.sun.jna.*;
import com.sun.jna.ptr.IntByReference;
public class MyClassWrapper {
public interface MyLibrary extends Library {
MyLibrary INSTANCE = Native.load("myclass", MyLibrary.class);
int Add(int a, int b);
}
public int add(int a, int b) {
IntByReference aRef = new IntByReference(a);
IntByReference bRef = new IntByReference(b);
return MyLibrary.INSTANCE.Add(aRef.getPointer().intValue(), bRef.getPointer().intValue());
}
public static void main(String[] args) {
MyClassWrapper myClassWrapper = new MyClassWrapper();
int result = myClassWrapper.add(3, 4);
System.out.println("Result: " + result);
}
}
- 编译并运行Java程序:
javac MyClassWrapper.java
java MyClassWrapper
这两种方法都可以实现在Java中调用C#方法并传递参数。注意,这里的示例依赖于C#方法Add接受两个整数参数并返回它们的和。你可以根据需要修改C#方法的实现和参数类型。