001    /*
002            Copyright (c) 2009 Olivier Chafik, All Rights Reserved
003            
004            This file is part of JNAerator (http://jnaerator.googlecode.com/).
005            
006            JNAerator is free software: you can redistribute it and/or modify
007            it under the terms of the GNU Lesser General Public License as published by
008            the Free Software Foundation, either version 3 of the License, or
009            (at your option) any later version.
010            
011            JNAerator is distributed in the hope that it will be useful,
012            but WITHOUT ANY WARRANTY; without even the implied warranty of
013            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014            GNU Lesser General Public License for more details.
015            
016            You should have received a copy of the GNU Lesser General Public License
017            along with JNAerator.  If not, see <http://www.gnu.org/licenses/>.
018    */
019    package com.ochafik.lang.jnaerator.runtime.globals;
020    
021    import com.ochafik.util.string.StringUtils;
022    import com.sun.jna.NativeLibrary;
023    import com.sun.jna.Pointer;
024    import com.sun.jna.PointerType;
025    
026    public abstract class GlobalPrimitive<T extends PointerType> extends Global {
027            protected final Class<T> type;
028            protected boolean indirected = false;
029            public GlobalPrimitive(NativeLibrary library, Class<T> type, String... symbols) {
030                    super(library, symbols);
031                    this.type = type;
032            }
033            protected T value;
034            protected T getValue() {
035                    if (value == null) {
036                            try {
037                                    value = type.newInstance();
038                            } catch (Exception e) {
039                                    throw new RuntimeException("Failed to instantiate pointer to " + StringUtils.implode(symbols, "/"), e);
040                            }
041                            Pointer pointer = getPointer();
042                            if (indirected) {
043                                    pointer = pointer.getPointer(0);
044                            }
045                            value.setPointer(pointer);
046                    }
047                    return value;
048            }
049            @Override
050            public String toString() {
051                    try {
052                            return String.valueOf(getClass().getMethod("get").invoke(this));
053                    } catch (Throwable t) {
054                            return super.toString();
055                    }
056            }
057    }