如何在jnr ffi中将结构体与结构体一起使用 [英] How to use a struct with a struct in jnr ffi
问题描述
我有以下C代码:
#include <stdio.h>
struct Second {
int a_number;
};
struct Top {
struct Second second;
};
void lets_go(struct Top *top) {
printf("The number is %d\n", top->second.a_number);
}
我想从Java中做到这一点:
And I want to do this from Java:
int main(void) {
struct Top top = {{8}};
lets_go(&top);
}
我也想使用 jnr-ffi ,所以我查看了测试并结束了与此:
I also want to use jnr-ffi, so I looked at the tests and ended up with this:
package structs.playing;
import structs.playing.Program.Test.Top;
import structs.playing.Program.Test.Second;
import jnr.ffi.LibraryLoader;
import jnr.ffi.Runtime;
import jnr.ffi.Struct;
public final class Program {
public static interface Test {
void lets_go(Top top);
public static final class Second extends Struct {
public final Signed32 a_number = new Signed32();
public Second(final Runtime runtime) {
super(runtime);
}
}
public static final class Top extends Struct {
public Second second;
public Top(final Runtime runtime) {
super(runtime);
}
}
}
public static void main(final String[] args) {
Test test = LibraryLoader.create(Test.class).load("test");
Runtime runtime = Runtime.getRuntime(test);
Top top = new Top(runtime);
Second second = new Second(runtime);
top.second = second;
second.a_number.set(7);
test.lets_go(top);
}
}
问题是 a_number
的值根本没有设置,所以我在输出中得到了一个垃圾值,例如:
The problem is that the value of a_number
is not set at all so I get a junk value in the output, for example:
The number is 46645760
那么我如何与C代码中的代码一样?
So how do I get the same as in my C code?
推荐答案
我已经弄清楚了(顺便说一句,我知道成员应该是私有的并且包装在属性中,但是我想使代码片段尽可能小尽可能不是生产质量代码)...
I have figured it out (by the way, I am aware that the members should be private and wrapped in properties but I wanted to make the code snippet as small as possible, this is not production quality code)...
If you put a Pointer member variable into the struct you can use it's memory when you construct the sub-ordinate Struct like so...
package structs.playing;
import structs.playing.Program.Test.Top;
import jnr.ffi.LibraryLoader;
import jnr.ffi.Runtime;
import jnr.ffi.Struct;
public final class Program {
public static interface Test {
void lets_go(Top top);
public static final class Second extends Struct {
public final Signed32 a_number = new Signed32();
public Second(final Runtime runtime) {
super(runtime);
}
}
public static final class Top extends Struct {
private final Pointer secondPointer = new Pointer();
public final Second second;
public Top(final Runtime runtime) {
super(runtime);
second = new Second(runtime);
second.useMemory(secondPointer.getMemory());
}
}
}
public static void main(final String[] args) {
Test test = LibraryLoader.create(Test.class).load("test");
Runtime runtime = Runtime.getRuntime(test);
Top top = new Top(runtime);
top.second.a_number.set(8);
test.lets_go(top);
}
}
这篇关于如何在jnr ffi中将结构体与结构体一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!