部分内容引用自网站:https://www.ibm.com/developerworks/cn/java/j-lo-cpp/index.html
GitHub: https://github.com/bytedeco/javacpp
如有侵权请联系笔者删除

JavaCPP是一个开源库,它提供了在 Java 中高效访问本地 C++的方法。采用 JNI 技术实现,所以支持所有 Java 实现包括 Android 系统,Avian 和 RoboVM。

为了调用本地方法,JavaCPP 生成了对应的 JNI 代码,并且把这些代码输入到 C++编译器,用来构建本地库。使用了 Annotations 特性的 Java 代码在运行时会自动调用 Loader.load() 方法从 Java 资源里载入本地库,这里指的资源是工程构建过程中配置好的。

示例:
这是一个简单的注入/读出方法,类似于 JavaBean 的工作方式。清单 1 所示的 LegacyLibrary.h 包含了 C++类。

清单 1. LegacyLibrary.h

#include <string>
namespace LegacyLibrary {
 	class LegacyClass {
     public:
 	const std::string& get_property() { return property; }
 	void set_property(const std::string& property) { this->property = property; }
 	std::string property;
 	};
}

接下来定义一个 Java 类,驱动 JavaCPP 来完成调用 C++代码。

清单 2. LegacyLibrary.java

import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
 
@Platform(include="LegacyLibrary.h")
@Namespace("LegacyLibrary")
public class LegacyLibrary {
 	public static class LegacyClass extends Pointer {
 	static { Loader.load(); }
 	public LegacyClass() { allocate(); }
 	private native void allocate();
 
 	// to call the getter and setter functions 
 	public native @StdString String get_property(); public native void set_property(String property);
 
	 // to access the member variable directly
 	public native @StdString String property(); public native void property(String property);
 }
 
 	public static void main(String[] args) {
 	// Pointer objects allocated in Java get deallocated once they become unreachable,
 	// but C++ destructors can still be called in a timely fashion with Pointer.deallocate()
 	LegacyClass l = new LegacyClass();
 	l.set_property("Hello World!");
 	System.out.println(l.property());
 }
}

以上两个类放在一个目录下面,接下来运行一系列编译指令,如清单 3 所示。

清单 3. 运行命令

$ javac -cp javacpp.jar LegacyLibrary.java 
$ java -jar javacpp.jar LegacyLibrary
$ java -cp javacpp.jar LegacyLibrary
Hello World!

我们看到清单 3 最后运行输出了一行“Hello World!”,这是 LegacyLibrary 类里面定义好的,通过一个 setter 方法注入字符串,getter 方法读出字符串。

上述内容都是引用自网站https://www.ibm.com/developerworks/cn/java/j-lo-cpp/index.html

光看别人的东西还是一知半解,所以笔者亲自动手试了一下,发现总是生成不了dll文件,在这里详细记录一下,仅供参考。欢迎各位讨论

第一步:
参照上述内容创建 Legacylibrary.h LegacyLibrary.java文件并将其和 javacpp.jar 文件放在一个文件夹里。

第二步:
打开VS的本机命令工具提示窗口(和Windows命令行窗口一样),用次命令窗口进入到以上三个文件所在的文件夹目录下,再用

$ javac -cp javacpp.jar LegacyLibrary.java 
$ java -jar javacpp.jar LegacyLibrary
$ java -cp javacpp.jar LegacyLibrary

这三条命令去生成 dll 文件库。
注意: 此处必须使用VS下的命令行进行操作,笔者此前使用Windows自带命令行一直没有成功,在执行第二条命令时会报“找不到指定文件”的错误。

VS下的命令行窗口启动如下图:
在这里插入图片描述
点击打开文件夹并选择对应的32位或64位工具。(打开命令行窗口时,若上方出现 Cannot determine the location of the VS Common Tools Folder,则需要在环境变量的 path中设置值:c:\windows\system32)

进入三个文件所在的文件夹及执行第一步编译操作:
在这里插入图片描述
生成 dll 文件:
在这里插入图片描述
在这里插入图片描述
此时程序所在文件夹会生成一个子文件夹“windows-x86_64”,在此文件夹下会有生成的动态链接库以及相关文件。
在这里插入图片描述
执行程序:
在这里插入图片描述
生成动态链接库后将文件夹“windows-x86_64”整体粘贴到java项目下的 src 目录下,并加载 javacpp.jar 包然后运行,显示成功。
在这里插入图片描述

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐