Java 访问 C++ 方法 JavaCPP
2023-03-09 22:01:56 时间
JavaCPP提供了在Java中高效访问本地C++的方法。采用JNI技术实现,支持所有Java实现包括Android系统,Avian 和 RoboVM。
JavaCPP提供了一系列的Annotation将Java代码映射到C++代码,并使用一个可执行的jar包将C++代码转化为可以从JVM内调用的动态链接库文件。
Maven:
- <dependency>
- <groupId>org.bytedeco</groupId>
- <artifactId>javacpp</artifactId>
- <version>0.11</version>
- </dependency>
使用方法:
C++:
- #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:
- 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());
- }
- }
相关文章
- Java要抛弃祖宗的基业,Java程序员危险了!
- 十大 Java 语言特性
- JVM 三色标记算法,原来是这么回事!
- 聊聊 Spring 事务控制策略以及 @Transactional 失效问题避坑
- 写给 Java 程序员的前端 Promise 教程
- 写给 Java 程序员的前端 Promise 教程,你学会了吗?
- Java 中为什么不全部使用 Static 方法?
- Java 池化技术你了解多少?
- Java 服务 Docker 容器化优秀实践
- Spring Boot + EasyExcel导入导出,简直太好用了!
- 我们一起聊聊 Java 内存泄漏
- CentOS 下安装 Docker 极简教程
- JDK 19 功能集冻结:Java 19 只有七个新特性
- 关于 CMS 垃圾回收器,你真的懂了吗?
- 为什么会有这么多编程语言?
- 改善Java代码的八个建议
- 接口流量突增,如何做好性能优化?
- Java 以编程方式创建JAR文件
- POJO、Java Bean是如何定义的
- Spring 的 Bean 明明设置了 Scope 为 Prototype,为什么还是只能获取到单例对象?