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 小时前
Cypress vs Playwright vs Selenium:现代Web自动化测试框架深度评测
java·前端·网络·人工智能·python·selenium·测试工具
uzong5 小时前
程序员从大厂回重庆工作一年
java·后端·面试
kyle~5 小时前
C++---value_type 解决泛型编程中的类型信息获取问题
java·开发语言·c++
NiNi_suanfa8 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
信奥胡老师8 小时前
苹果电脑(mac系统)安装vscode与配置c++环境,并可以使用万能头文件全流程
c++·ide·vscode·macos·编辑器
妖灵翎幺8 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
开心香辣派小星9 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
Halo_tjn9 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
star _chen9 小时前
C++实现完美洗牌算法
开发语言·c++·算法
摆烂z9 小时前
Docker与Jib(maven插件版)实战
java