我是 JAVA 编程和 JNI 的新手。 如何使用JNI在Java程序中调用getpid() C库函数? 我经历了以下帖子 How can a Java program get its own process ID? 但无法运行程序。 提前致谢
我写了以下程序
public class ProcessId
{
public static void main(String[] args) {
CLibrary clib = (CLibrary) Native.loadLibrary("c",Library.class);
clib.getpid();
System.out.println("Process Id is "+getpid());
}
}
我收到以下错误
1)库无法解析为类型
3)ProcessId类型的getpid()方法未定义
上面提到的帖子讨论了 platform.jar 文件。我从http://grepcode.com/snapshot/repo1.maven.org/maven2/net.java.dev.jna/platform/3.4.0下载了一个并包含在项目库中。但还是没解决..
最佳答案
Mat 和 Thomas,感谢您的帮助..
我设法从Java调用C库函数..
按照我采取的步骤。
步骤 1) 从 GitHub 下载 jna.jar。 https://github.com/twall/jna
第 2 步) 在项目库中添加上述 jar 文件
步骤3)编写以下代码
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
/** Simple example of native library declaration and usage. */
public class ProcessId {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary(
(Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
void printf(String format, Object... args);
int getpid();
}
public static void main(String[] args) {
CLibrary.INSTANCE.printf("Hello, World\n");
System.out.println("My Process id is "+ CLibrary.INSTANCE.getpid());
for (int i = 0; i < args.length; i++) {
CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
}
}
}
它正在工作!!!
关于java-native-interface - 如何使用JNI在Java程序中调用getpid() C库函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18160935/