1

我正在尝试将 JNA 与 Mac OS X 一起使用。我想访问一个 Carbon 库,没有 Cocoa 等价物,所以 Rococoa 帮不了我(我认为......)

尝试调用需要 CFStringRef 作为参数的 Carbon 函数时,我被卡住了。如何从 Java 字符串创建 CFStringRef?

到目前为止,这是我的尝试:

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);
        }
    }

}
4

1 回答 1

1

我想出了这个:

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

有了这个定义:

CFStringRef CFStringCreateWithCharacters(
        Void alloc, //  always pass NULL
        char[] chars,
        CFIndex numChars
);
于 2009-10-26T18:14:29.797 回答