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

相关推荐
_一条咸鱼_5 小时前
揭秘 Android TextInputLayout:从源码深度剖析其使用原理
android·java·面试
_一条咸鱼_5 小时前
揭秘!Android VideoView 使用原理大起底
android·java·面试
_一条咸鱼_5 小时前
深度揭秘!Android TextView 使用原理全解析
android·java·面试
_一条咸鱼_5 小时前
深度剖析:Android Canvas 使用原理全揭秘
android·java·面试
_一条咸鱼_5 小时前
深度剖析!Android TextureView 使用原理全揭秘
android·java·面试
_一条咸鱼_5 小时前
揭秘!Android CheckBox 使用原理全解析
android·java·面试
_一条咸鱼_5 小时前
深度揭秘:Android Toolbar 使用原理的源码级剖析
android·java·面试
_一条咸鱼_5 小时前
揭秘 Java ArrayList:从源码深度剖析其使用原理
android·java·面试