【问题标题】:Converting String to Pointer for JNA将字符串转换为 JNA 的指针
【发布时间】:2012-04-26 20:46:16
【问题描述】:

我正在尝试使用 JNA 在 Windows 中查询文件的有效权限。最终,我计划使用GetEffectiveRightsFromAcl function,但要这样做,我需要提供一个指向已填充TRUSTEE structure 的指针。 JNA 平台(platform.jar)似乎没有定义这个结构,所以我试图自己定义它。这是我目前所拥有的:

public static class TRUSTEE extends Structure {
    public TRUSTEE() {
        super();
    }
    public TRUSTEE(Pointer p) {
        super(p);
        read();
    }

    public Pointer pMultipleTrustee;
    public int MultipleTrusteeOperation;
    public int TrusteeForm;
    public int TrusteeType;
    public Pointer ptstrName;
}

我正在尝试填充这样的结构:

private TRUSTEE createTrusteeForCurrentUser() {
    TRUSTEE result = new TRUSTEE();
    result.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_NAME;
    result.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_USER;

    String strName = "CURRENT_USER";
    // How can I set result.ptstrName using strName?
}

This Google Groups thread 建议在调用 char * 时在结构中使用 String 字段。但是,我认为这不适合我的情况,考虑到 ptstrName 字段可以指向不同类型的事物,具体取决于 TrusteeForm 的值。所以,我想我需要以某种方式从String 转换为Pointer。我在 JNA 中找到了 NativeString 类,它可以工作,除了它是一个包私有类。

将Java String 转换为本机格式并获得Pointer 的推荐方法是什么?我是否为TRUSTEE 结构使用了正确的数据类型?我对 JNA 有点陌生,所以如果我遗漏了一些明显的东西,请见谅。

更新

我找到了解决问题的方法,但如果有人有更好的解决方案,我仍然想听听。

【问题讨论】:

    标签: java winapi jna


    【解决方案1】:

    【讨论】:

    • 我知道我需要一个Pointer,我想问题更多的是如何将Java String 转换为本机格式并获得一个Pointer 对象。
    【解决方案2】:

    我通过复制 package-private NativeString 类的源代码并在我的项目中创建一个公共副本解决了这个问题。由于在构造函数中使用了包私有方法,我不得不做一个小改动。

    更新:正如@fragorl 在 cmets 中指出的那样,下面显示的 NativeString 的实现现在已经过时了。


    用法:

    private static TRUSTEE createTrusteeForCurrentUser() {
        TRUSTEE result = new TRUSTEE();
        result.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_NAME;
        result.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_USER;
        result.ptstrName = new NativeString("CURRENT_USER",true).getPointer();
        result.write();
        return result;
    }
    

    NativeString.java:

    /** Provides a temporary allocation of an immutable C string 
     * (<code>const char*</code> or <code>const wchar_t*</code>) for use when 
     * converting a Java String into a native memory function argument.  
     *
     * @author  Todd Fast, todd.fast@sun.com
     * @author twall@users.sf.net
     */
    public class NativeString implements CharSequence, Comparable {
    
        private Pointer pointer;
        private boolean wide;
    
        /** Create a native string (NUL-terminated array of <code>char</code>).<p>
         * If the system property <code>jna.encoding</code> is set, its value will
         * be used to encode the native string.  If not set or if the encoding
         * is unavailable, the default platform encoding will be used. 
         */
        public NativeString(String string) {
            this(string, false);
        }
    
        /** Create a native string as a NUL-terminated array of <code>wchar_t</code>
         * (if <code>wide</code> is true) or <code>char</code>.<p>
         * If the system property <code>jna.encoding</code> is set, its value will
         * be used to encode the native <code>char</code>string.  
         * If not set or if the encoding is unavailable, the default platform 
         * encoding will be used. 
         * 
         * @param string value to write to native memory
         * @param wide whether to store the String as <code>wchar_t</code>
         */
        public NativeString(String string, boolean wide) {
            if (string == null) {
                throw new NullPointerException("String must not be null");
            }
            // Allocate the memory to hold the string.  Note, we have to
            // make this 1 element longer in order to accommodate the terminating 
            // NUL (which is generated in Pointer.setString()).
            this.wide = wide;
            if (wide) {
                int len = (string.length() + 1 ) * Native.WCHAR_SIZE;
                pointer = new Memory(len);
                pointer.setString(0, string, true);
            }
            else {
                byte[] data = Native.toByteArray(string);
                pointer = new Memory(data.length + 1);
                pointer.write(0, data, 0, data.length);
                pointer.setByte(data.length, (byte)0);
            }
        }
    
        public int hashCode() {
            return toString().hashCode();
        }
    
        public boolean equals(Object other) {
    
            if (other instanceof CharSequence) {
                return compareTo(other) == 0;
            }
            return false;
        }
    
        public String toString() {
            String s = wide ? "const wchar_t*" : "const char*";
            s += "(" + pointer.getString(0, wide) + ")";
            return s;
        }
    
        public Pointer getPointer() {
            return pointer;
        }
    
        public char charAt(int index) {
            return toString().charAt(index);
        }
    
        public int length() {
            return toString().length();
        }
    
        public CharSequence subSequence(int start, int end) {
            return CharBuffer.wrap(toString()).subSequence(start, end);
        }
    
        public int compareTo(Object other) {
    
            if (other == null)
                return 1;
    
            return toString().compareTo(other.toString());
        }
    }
    

    【讨论】:

    • 谢谢,这似乎是“正确”的做法。一个问题 - 为什么不使用 1-arg NativeString 构造函数,而不是 2-arg 构造函数?
    • @fragorl 对于我的应用程序,我使用的是宽字符 (Unicode) 字符串,因此我需要将 wide 参数设置为 true。 1-arg 构造函数将其设置为false
    • 啊,我的错,我正在查看最新版本的 jna,他们更改了 1-arg 构造函数。它现在显示为:this(string, Native.getDefaultStringEncoding());。但是你这里有旧版本的源代码——当然,你的帖子是 2012 年的,哎呀>
    • @fragorl - 很高兴知道。我在答案中做了注释。
    【解决方案3】:

    假设您希望在本机端使用 char *(如果字符串包含非 ascii 字符,您可能需要分配更多内存),

    String myString = "CURRENT_USER";
    Pointer m = new Memory(myString.length() + 1); // WARNING: assumes ascii-only string
    m.setString(0, myString); 
    

    然后,您可以在需要引用“本机”字符串的任何地方使用m

    对于宽字符串 (wchar_t *),

    String myString = "CURRENT_USER";
    Pointer m = new Memory(Native.WCHAR_SIZE * (myString.length() + 1));
    m.setWideString(0, myString);
    

    【讨论】:

    • setString(offset, value) 调用 setString(offset, value, Native.getDefaultStringEncoding())。假设 Native.getDefaultStringEncoding() 总是返回每个字符仅使用 1 个字节的格式似乎不安全,这是您分配的?
    • Pointer m = new Memory(Native.WCHAR_SIZE * (myString.length() + 1); 缺少括号,这是否意味着 Pointer m = new Memory(Native.WCHAR_SIZE * (myString .length() + 1)); ?
    猜你喜欢
    • 2013-03-06
    • 2011-12-12
    • 2019-05-09
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多