2013-03-24 60 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,概念都是一樣的。

相關問題