我试图摆脱在Mac OS X上使用JNA的束缚。我想访问一个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);
}
}
}
最佳答案
我想出了这个:
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
);