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

相关推荐
saltymilk6 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥6 小时前
C++ lambda 匿名函数
c++
RainbowSea6 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea7 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
考虑考虑10 小时前
Jpa使用union all
java·spring boot·后端
用户37215742613511 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
浮游本尊12 小时前
Java学习第22天 - 云原生与容器化
java
沐怡旸12 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥13 小时前
C++ 内存管理
c++
渣哥14 小时前
原来 Java 里线程安全集合有这么多种
java