我有一个C ++库,该库使用包含向量的结构。我很难确定通过JNA从Java访问此内容的正确方法。
我的C ++结构:
#include <vector>
struct topic {
char* src_id;
char* dest_id;
int32_t num;
std::vector<char*> names;
};
我的Java类:
public final class Topic extends Structure {
public String src_id;
public String dest_id;
public int num;
public String[] names; // This doesn't work
public Topic() {
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "src_id", "dest_id", "num", "names" });
}
}
答案 0 :(得分:1)
此解决方案对我有用:
package com.example;
import java.util.Arrays;
import java.util.List;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.StringArray;
import com.sun.jna.Structure;
public class Example {
public interface CLibrary extends Library {
public static class Topic extends Structure {
public static class ByReference extends Topic implements Structure.ByReference {
}
public String src_id;
public String dest_id;
public int num;
public int numVals;
public Pointer names; // char**
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(new String[] { "src_id", "dest_id", "num", "numVals", "names" });
}
}
public void sendTopic(Topic.ByReference pVal);
}
public static void main(String[] args) {
final CLibrary clib = Native.loadLibrary("example.dll", CLibrary.class);
final String[] myArray = new String[5];
myArray[0] = "one";
myArray[1] = "two";
myArray[2] = "three";
myArray[3] = "four";
myArray[4] = "five";
CLibrary.Topic.ByReference ref = new CLibrary.Topic.ByReference();
ref.numVals = 5;
ref.names = new StringArray(myArray);
clib.sendTopic(ref);
}
}
答案 1 :(得分:0)
您可以使用Pointer并使用here的public StringArray(String[] strings)
传递StringArray
public String src_id;
public String dest_id;
public int num;
public Pointer names;
String[] namesArray= new String[2];
//Assign two names to namesArray
//Construct StringArray with namesArray and pass it to Pointer
names = new StringArray(namesArray);