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端
-
定义库加载类
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);
}
-
定义结构体接收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 { }
}
-
执行测试
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()); }
}
-
查看打印
