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. 查看打印

相关推荐
zh_xuan1 小时前
c++ 单例模式
开发语言·c++·单例模式
coderSong25681 小时前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
Mr_Air_Boy2 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
豆沙沙包?2 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
年老体衰按不动键盘3 小时前
快速部署和启动Vue3项目
java·javascript·vue
咖啡啡不加糖3 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存
liuyang-neu3 小时前
java内存模型JMM
java·开发语言
利刃大大3 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
UFIT3 小时前
NoSQL之redis哨兵
java·前端·算法
喜欢吃燃面3 小时前
C++刷题:日期模拟(1)
c++·学习·算法