当前位置: 首页 > news >正文

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);
}
  1. 定义结构体接收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 {
    }
}
  1. 执行测试
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());
    }
}

  1. 查看打印

在这里插入图片描述

相关文章:

  • Python数据结构综合应用:实战案例与练习
  • keycloak - 开发环境的配置持久化
  • C++继承
  • springboot博客系统详解与实现(后端实现)
  • 《论湖仓一体架构及其应用》审题技巧 - 系统架构设计师
  • https:原理
  • C++复习专题——泛型编程(模版),包括模版的全特化和偏特化
  • 29.C++多态 2 (重载,重定义(隐藏),重写 三者的区别)
  • git常用命令(时常更新)
  • 医疗影像分割中的半监督学习实践:从算法原理到CT/MRI实战
  • MybatisPlus-扩展功能-枚举处理器
  • 【linux配置】 修改内核网络参数
  • Linux之loop设备(Loop Devices in Linux)
  • 冯诺依曼体系结构和操作系统
  • 逆向pyinstaller打包的exe软件,获取python源码(4)
  • Vue2+OpenLayers实现右键菜单功能(提供Gitee源码)
  • 【OMCI实践】ONT上线过程的omci消息(六)
  • 2、并行和并发有什么区别【中高频】
  • Linux | YUM / RPM 常用命令
  • CSDN 博客:CC++ 内存管理详解
  • 现在有哪些推广平台/seo需要培训才能找到工作吗
  • 厦门关键词优化服务/关键词优化排名公司
  • 深圳营销型网站制作公司/乔拓云智能建站系统
  • 怎么做非法网站/百度大数据官网入口
  • 公司网站建设定金计入什么科目/女教师遭网课入侵直播录屏曝
  • 怎么用WordPress快速建站/电商运营的基本内容