2

I'm sure someone out there knows how to get the address of an array using the Unsafe class. I've looked at related posts and there wasn't actually an answer.

static Unsafe _u;  
static int Atoi8(char[] s, int i0, int cb)  {
    int n = 0;
    // loop to process the valid number chars.
    int baseOffset = _u.arrayBaseOffset(s.getClass());  <-- returns 16 oops!
    for (int i=i0 ; i<i0+cb ; ++i) {
        char ch = _u.getChar(baseOffset + i);
        n = n*10 + ((ch <= '0') ? 0 : ch - '0');
    }
    return n;
}   

PLEASE Lets not make this a discussion about the perils of unsafe code, pre-optimzation, using a different language, or performance vs maintainability!

johnnycrash
  • 5,184
  • 5
  • 34
  • 58
  • 2
    I'm not sure what you're asking for is really possible, according to [http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/](http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/) the JVM's GC has a tendency to move things around behind your back. Even if you got the address, it would be difficult to guarantee its validity for any length of time. – azurefrog Jul 16 '15 at 19:03
  • Unsafe.getChar takes an address. How do I get the address of the first element in char[] s? – johnnycrash Jul 16 '15 at 19:03
  • @azure Yeah, I'm aware of the moving around bit. If this crashes a few times during testing I don't care. If the testing works, I have ways to deal with that. – johnnycrash Jul 16 '15 at 19:04
  • What occurs when the current code is run? – FThompson Jul 16 '15 at 19:13
  • Also, have you tried using `#arrayIndexScale`? From the `#arrayBaseOffset` docs: *If #arrayIndexScale returns a non-zero value for the same class, you may use that scale factor, together with this base offset, to form new offsets to access elements of arrays of the given class.* – FThompson Jul 16 '15 at 19:14
  • @Vulcan. Its a byte array, i assumed scale was 1. I'll double check it. – johnnycrash Jul 16 '15 at 19:16
  • Would something like this help you? http://stackoverflow.com/questions/7060215/how-can-i-get-the-memory-location-of-a-object-in-java – Adam Jul 16 '15 at 19:19
  • @johnnycrash `char` is a two-byte primitive so I'd suspect the scale is 2, but I'm not sure that's the only step necessary to make this work. – FThompson Jul 16 '15 at 19:22
  • @Vulcan. You could be right! – johnnycrash Jul 16 '15 at 19:26
  • @Adam. I tried that. Doesn't like to be passed a char[] – johnnycrash Jul 16 '15 at 19:27

0 Answers0