使用JNA创建CFString对象
-
06-07-2019 - |
题
我正试图在Mac OS X上使用JNA。我想访问一个Carbon库,没有Cocoa等价物,所以Rococoa无法帮助我(我想......)
我在尝试调用需要CFStringRef作为参数的Carbon函数时遇到困难。如何从Java String创建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
);
不隶属于 StackOverflow