I'm using a C# dll library in my java code, this library functions is called using jna, some of the parameters of these functions contain Structs, and to create an equivalent parameter in Java I have to create a static abstract class
which inherits Structure
class and it must contains all the variables that exists in the struct that I'm trying to create an equivalent to, for more illustration:
in C#:
struct SDK_AutoConfig {
int iDay;
int iHour;
int isec;
};
and there is a function which is like:
run_auto_config(int x, SDK_AutoConfig auto)
So, to call such function in Java:
// Declaring the Struct
public static abstract class SDK_AutoConfig extends Structure{
public int iDay;
public int iHour;
public int isec;
}
// Instantiating it
SDK_AutoConfig auto = new SDK_AutoConfig() {
@Override
protected List getFieldOrder() {
List<Object> list = new ArrayList<>();
return list;
}
};
// And to call the function
run_auto_config(65, auto);
tell here everything is OK, but when there is another struct
declared as a variable inside the SDK_AutoConfig
struct
, I can't deal with, what I tried first is to regularly pass it:
public static abstract class SDK_AutoConfig extends Structure{
public int iDay;
public int iHour;
public int isec;
public OTHER_STRUCT struct_two;
}
but when doing that I get:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid Structure field in class Test$1, field name 'struct_two' (class Test$SDK_AutoConfig$OTHER_STRUCT): Can't instantiate class Test$SDK_AutoConfig$OTHER_STRUCT (java.lang.InstantiationException)
So, I tried to instantiate it first then pass it to the constructor of SDK_AutoConfig
:
OTHER_STRUCT mStruct = new OTHER_STRUCT() {
@Override
protected List getFieldOrder() {
List<Object> list = new ArrayList<>();
return list;
}
};
SDK_AutoConfig auto = new SDK_AutoConfig(mStruct) {
@Override
protected List getFieldOrder() {
List<Object> list = new ArrayList<>();
return list;
}
};
// Then, inside the Class
public static abstract class SDK_AutoConfig extends Structure{
public OTHER_STRUCT struct_two;
public DeviceDate(OTHER_STRUCT mStruct){
struct_two = mStruct;
}
public int iDay;
public int iHour;
public int isec;
}
but I got the same exact Exception. So, how to solve that?
Move your anonymous instance creation code into your Structure
class and remove the abstract
modifier. Then you can nest the different structures however you need to.
As for the C# DLL exported API, as long as your method declarations are decorated with extern "C"
and use only C constructs, they should be exported in a compatible manner and thus usable by JNA.