2013-03-24 687 views
1

我想问一下关于下面的源代码,我简化了它以使它更易于理解。如何将PointerByReference地址传递给JNA中的一个结构

C代码

struct test 
{ 
int test1; 
}; 

int create_context(test **context); 
int use_context(test *context); 

Java代码

public static class test extends Structure { 
    public int test1; 
    public test() { 
     super(); 
    } 
    public test()(Pointer p) { 
     super(p); 
    } 
    protected List getFieldOrder() { 
     return Arrays.asList("test1"); 
    } 
    public test(int test1) { 
     super(); 
     this.test1 = test1; 
    } 
    public static class ByReference extends test implements Structure.ByReference { 

    }; 
    public static class ByValue extends test implements Structure.ByValue { 

    }; 
} 
public static native int create_context(PointerByReference context); 
public static native int use_context(TestLibrary.test context); 

我访问结构中这样的java,

PointerByReference contextPointer = new PointerByReference(); 
    int status = INSTANCE.create_context(contextPointer); 
    test context = new test(contextPointer.getValue()); 
    status = INCTANCE.use_context(context); 

当我调试这个在Visual Studio中,我所看到的,对于create_context和use_context,使用不同的内存地址。 当我设置int test1的值,它是正确的,但我想知道,为什么上下文的地址是不同的。有没有人有一个想法?这不会导致记忆问题?或者任何想法我做错了什么? 谢谢瓦伦蒂娜

+0

你问为什么'test **'类型的变量的值与'test *'类型的变量不同? – technomage 2013-03-24 14:32:08

+0

是的,没有:)让我们说,为什么地址不同,即使我使用相同的指针。任何想法? – Valentina 2013-03-24 16:24:58

+0

因为'test **'中的值是'test *'中值的地址。 – technomage 2013-03-24 16:44:57

回答

1

你们已经选择了一般使用struct test*的惯例,所以我们将与此合作。

你的原生代码需要看起来像这样:

int create_context(struct test **context) { 
    *context = (struct test *)malloc(sizeof(test)); 
    // initialize here... 
    return 0; 
} 

当你调用create_context,你必须在传递一个指针的地址

struct test* test_ptr; 

create_context(&test_ptr); 

test_ptr->some_field = ...; // operate on your struct via pointer 

重要的是要保持平直时很重要您按值(struct test),参考(struct test*)或参考地址(struct test**)使用该结构。无论您的使用是使用C还是使用Java,概念都是一样的。

相关问题