views:

278

answers:

1

I'm trying to get the hang of using JNA with Mac OS X. I want to access a Carbon library, for which there is no Cocoa equivalent, so Rococoa can't help me (I think...)

I'm stuck when trying to call a Carbon function that requires CFStringRef as a parameter. How can I create a CFStringRef from a Java String?

Here's my attempt so far:

import com.sun.jna.Library; 
import com.sun.jna.Native; 
import com.sun.jna.Pointer; 
import com.sun.jna.ptr.PointerByReference;

public class JnaTest {

    public interface AXUIElement extends Library {
        AXUIElement INSTANCE = (AXUIElement) Native.loadLibrary("Carbon", AXUIElement.class);
        Pointer AXUIElementCreateApplication(int pid);
        // HELP: String is clearly wrong here but what should I use?
        int AXUIElementCopyAttributeValue(Pointer element, String attribute, PointerByReference value);
    }

    public static void main(String[] args) {
        final int pid = 5264; // make sure this is a valid pid
        final Pointer elementRef = AXUIElement.INSTANCE.AXUIElementCreateApplication(pid);
        // HELP: attribute should be of type CFStringRef
        final String attribute = "AXWindows";
        PointerByReference value = new PointerByReference();
        final int error = AXUIElement.INSTANCE.AXUIElementCopyAttributeValue(elementRef, attribute, value);
        if (error == 0) {
            System.out.println("value = " + value);
        } else {
            System.out.println("Failure: " + error);
        }
    }

}
A: 

I came up with this:

   public static CFStringRef toCFString(String s) {
        final char[] chars = s.toCharArray();
        int length = chars.length;
        return AXUIElement.INSTANCE.CFStringCreateWithCharacters(null, chars, AXAPI.createCFIndexFor(length));
    }

with this definition:

CFStringRef CFStringCreateWithCharacters(
        Void alloc, //  always pass NULL
        char[] chars,
        CFIndex numChars
);
Steve McLeod