001    /*
002     * To change this template, choose Tools | Templates
003     * and open the template in the editor.
004     */
005    
006    package org.bridj;
007    
008    import java.lang.reflect.Constructor;
009    import java.lang.reflect.Method;
010    
011    import static org.bridj.Pointer.*;
012    
013    /**
014     * Generic C function which invocation involves a bit of Java reflection.<br>
015     * To create a dynamic function, use {@link Pointer#asDynamicFunction(org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) } or {@link CRuntime#getDynamicFunctionFactory(org.bridj.NativeLibrary, org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[])  }.
016     * @author ochafik
017     * @param R Return type of the function (can be {@link java.lang.Void})
018     */
019    public abstract class DynamicFunction<R> extends Callback {
020        /// Don't GC the factory, which holds the native callback handle
021        DynamicFunctionFactory factory;
022        Method method;
023    
024        protected DynamicFunction() {}
025    
026        public R apply(Object... args) {
027            try {
028                return (R) method.invoke(this, args);
029            } catch (Throwable th) {
030                th.printStackTrace();
031                throw new RuntimeException("Failed to invoke callback" + " : " + th, th);
032            }
033        }
034    
035        @Override
036        public String toString() {
037            return method.toString();
038        }
039    
040    
041    }