JNA基础使用,调用C++返回结构体

C++端

test.h文件

#pragma once

struct RespInfo
{
    char* path;
    char* content;
    int statusCode;
};

extern "C" {
DLL_EXPORT void readInfo(char* path, RespInfo* respInfo);
}

test.cpp文件

#include "test.h"

void readInfo(char* path, RespInfo* respInfo)
{
    std::string res = "my resp content";
    char* resChar = new char [res.length() + 1];
    strcpy(resChar, res.c_str());
    int statusCode = 111;

    respInfo->path = path;
    respInfo->content = resChar;
    respInfo->statusCode = statusCode;
}

编写出DLL后,放到指定目录供JAVA加载调用。

Java端

  1. 定义库加载类

    package org.demo.apptest1.jnatest;

    import com.sun.jna.Library;
    import com.sun.jna.Native;
    import com.sun.jna.Platform;

    public interface ExportFuncLib extends Library {
    ExportFuncLib INSTANCE = Native.load(Platform.isWindows() ? "D:\Test.dll" : "/usr/lib/test.so", ExportFuncLib.class);

     void readInfo(String path, MyStruct myStruct);
    

    }

  2. 定义结构体接收C++返回

    package org.demo.apptest1.jnatest;

    import com.sun.jna.Structure;

    import java.util.ArrayList;
    import java.util.List;

    public class MyStruct extends Structure {
    public String path;
    public String content;
    public int statusCode;

     @Override
     protected List<String> getFieldOrder() {
         List<String> field = new ArrayList<>();
         field.add("path");
         field.add("content");
         field.add("statusCode");
         return field;
     }
    
     // 添加一个内部类,实现Structure.ByReference接口,用于通过引用传递
     public static class ByReference extends MyStruct implements Structure.ByReference {
     }
    

    }

  3. 执行测试

    package org.demo.apptest1.jnatest;

    import com.sun.jna.Native;

    public class DllTest {
    static {
    Native.setProtected(true);
    System.setProperty("jna.debug_load", "true");
    }

     public static void main(String[] args) {
         String path = "D://acc.file";
         MyStruct myStruct = new MyStruct();
    
         ExportFuncLib.INSTANCE.readInfo(path, myStruct);
    
         System.out.println(myStruct.toString());
     }
    

    }

  4. 查看打印

相关推荐
青衫一笔墨1 小时前
企业级大模型应用的Java-Python异构融合架构实践
java·人工智能·python·架构
m0_748238921 小时前
Java进阶:Docker
java·docker·eureka
励碼2 小时前
BUG: 解决新版本SpringBoot3.4.3在创建项目时勾选lombok但无法使用的问题
java·spring boot·bug·lombok
Vacant Seat2 小时前
矩阵-旋转图像
java·数据结构·算法·矩阵
柃歌2 小时前
【UCB CS 61B SP24】Lecture 14 - Data Structures 1: Disjoint Sets学习笔记
java·数据结构·笔记·学习·算法
Yang-Never2 小时前
OpenGL ES -> GLSurfaceView绘制点、线、三角形、正方形、圆(索引法绘制)
android·java·开发语言·kotlin·android studio
扫地僧0092 小时前
Java 面试题及答案整理,最新面试题
java·jvm·算法·面试
float_六七2 小时前
Java中JDK、JRE,JVM之间的关系
java
m0_748251352 小时前
java进阶1——JVM
java·开发语言·jvm
Cheese%%Fate2 小时前
【C++】面试常问八股
c++·面试