简体   繁体   中英

JNA Pass char* By Reference

DllExport void LoadString(char *myStr)
{
    cout << "Before: " << myStr << endl;
    LoadStringData(&myStr);
    cout << "After:" << myStr << endl;
}

and this in Java:

Pointer myStr = new Memory(Pointer.SIZE);
System.out.println(String.format("myStr Value: %s", myStr.getPointer(0).getString(0)));
this.Lib.LoadString(myStr);
System.out.println(String.format("myStr Value: %s", myStr.getPointer(0).getString(0)));

And this is the output:

myStr Value: ¸ï1
Before: Øî1
After:test
myStr Value: ¸ï1

So I can clearly see a garbage pointer being passed in, reallocated on C++ (After:test), but for some reason JNA isn't aware of the change.

These threads suggest what I'm doing is correct:

How to obtain a new Pointer in Java?

JNA Struct and Pointer mapping

And I've also tried PointerByReference (though to be honest, that acts like void**), but I'm throwing every idea I can get at it. However the threads above are about passing structs, not char*, but I can't see why JNA would care about the difference here.

Any ideas?

DllExport void LoadString(char **myStr)
{
    cout << "Before: " << *myStr << endl;
    LoadStringData(myStr);
    cout << "After:" << *myStr << endl;
}

Should work better to pass a reference to the memory (char* ) rather than the memory it self(char ), that way your changes make it back to Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM