protected <T extends CPPObject> Pointer<T> newCPPInstance( T instance, final Type type, int constructorId, Object... args) { Pointer<T> peer = null; try { final Class<T> typeClass = Utils.getClass(type); NativeLibrary lib = BridJ.getNativeLibrary(typeClass); if (BridJ.debug) info("Creating C++ instance of type " + type + " with args " + Arrays.asList(args)); Pointer.Releaser releaser = newCPPReleaser(type, typeClass, lib); long size = sizeOf(type, null); peer = (Pointer) Pointer.allocateBytes(PointerIO.getInstance(type), size, releaser).as(type); DynamicFunction constructor = constructorId == SKIP_CONSTRUCTOR ? null : getConstructor(typeClass, type, lib, constructorId); if (lib != null && CPPObject.class.isAssignableFrom(typeClass)) { installRegularVTablePtr(type, lib, peer); } else { // TODO ObjCObject : call alloc on class type !! } // Setting the C++ template parameters in the instance : int templateParametersCount = getTemplateParametersCount(typeClass); if (templateParametersCount > 0) { Object[] templateArgs = new Object[templateParametersCount]; System.arraycopy(args, 0, templateArgs, 0, templateParametersCount); setTemplateParameters(instance, typeClass, templateArgs); } // Calling the constructor with the non-template parameters : if (constructor != null) { Object[] consThisArgs = new Object[args.length - templateParametersCount + 1]; consThisArgs[0] = peer; System.arraycopy( args, templateParametersCount, consThisArgs, 1, args.length - templateParametersCount); constructor.apply(consThisArgs); } // Install synthetic virtual table and associate the Java instance to the corresponding native // pointer : if (CPPObject.class.isAssignableFrom(typeClass)) { if (installSyntheticVTablePtr(type, lib, peer)) BridJ.setJavaObjectFromNativePeer(peer.getPeer(), instance); } else { // TODO ObjCObject : call alloc on class type !! } return peer; } catch (Exception ex) { ex.printStackTrace(); if (peer != null) { peer.release(); } throw new RuntimeException("Failed to allocate new instance of type " + type, ex); } }
public AVResampleLibrary() throws IOException { lib = BridJ.getNativeLibrary(Lib.class); int libVersion = avresample_version(); majorVersion = (libVersion >> 16) & 0xff; minorVersion = (libVersion >> 8) & 0xff; microVersion = libVersion & 0xff; String version = String.format("%d.%d.%d", majorVersion, minorVersion, microVersion); File libFile = BridJ.getNativeLibraryFile(LIB_NAME); Logger.getLogger(getClass().getName()) .log( Level.INFO, "Loading {0} library, version {1}...", new Object[] {libFile.getAbsolutePath(), version}); if (majorVersion < MIN_MAJOR_VERSION || majorVersion > MAX_MAJOR_VERSION) throw new UnsatisfiedLinkError( "Unsupported version of the " + LIB_NAME + " native library. (" + MIN_MAJOR_VERSION + ".x.x <= required <= " + MAX_MAJOR_VERSION + ".x.x, found " + version + ")"); }
protected boolean installSyntheticVTablePtr(Type type, NativeLibrary library, Pointer<?> peer) { synchronized (syntheticVirtualTables) { VTable vtable = syntheticVirtualTables.get(type); if (vtable == null) { if (!typesThatDontNeedASyntheticVirtualTable.contains(type)) { List<VirtMeth> methods = new ArrayList<VirtMeth>(); listVirtualMethods(Utils.getClass(type), methods); boolean needsASyntheticVirtualTable = false; for (VirtMeth method : methods) if (!Modifier.isNative(method.implementation.getModifiers())) { needsASyntheticVirtualTable = true; break; } if (needsASyntheticVirtualTable) { Type parentType = Utils.getParent(type); Pointer<Pointer> parentVTablePtr = null; if (CPPObject.class.isAssignableFrom(Utils.getClass(parentType))) { parentVTablePtr = peer.getPointer(Pointer.class); if (BridJ.debug) { BridJ.info( "Found parent virtual table pointer = " + ptrToString(parentVTablePtr, library)); /*Pointer<Pointer> expectedParentVTablePtr = pointerToAddress(getVirtualTable(parentType, library), Pointer.class); if (expectedParentVTablePtr != null && !Utils.eq(parentVTablePtr, expectedParentVTablePtr)) BridJ.warning("Weird parent virtual table pointer : expected " + ptrToString(expectedParentVTablePtr, library) + ", got " + ptrToString(parentVTablePtr, library)); */ } // parentVTablePtr = pointerToAddress(getVirtualTable(parentType, library), // Pointer.class); } syntheticVirtualTables.put( type, vtable = synthetizeVirtualTable(type, parentVTablePtr, methods, library)); } else { typesThatDontNeedASyntheticVirtualTable.add(type); } } } if (vtable != null) { if (BridJ.debug) BridJ.info( "Installing synthetic vtable pointer " + vtable.ptr + " to instance at " + peer + " (type = " + Utils.toString(type) + ", " + vtable.callbacks.size() + " callbacks)"); peer.setPointer(vtable.ptr); return vtable.ptr != null; } else return false; } }
public synchronized MemoryOperators getMemoryOperators() { if (memoryOperators == null) { try { NativeLibrary libStdCpp = BridJ.getNativeLibrary("stdc++"); memoryOperators = new MemoryOperators(libStdCpp); } catch (Exception ex) { BridJ.error(null, ex); } } return memoryOperators; }
static { { OpenCLProbeLibrary probe = new OpenCLProbeLibrary(); try { if (!probe.isValid()) { String alt; if (Platform.is64Bits() && BridJ.getNativeLibraryFile(alt = "atiocl64") != null || BridJ.getNativeLibraryFile(alt = "atiocl32") != null || BridJ.getNativeLibraryFile(alt = "atiocl") != null) { log( Level.INFO, "Hacking around ATI's weird driver bugs (using atiocl library instead of OpenCL)", null); BridJ.setNativeLibraryActualName("OpenCL", alt); } } } finally { probe = null; BridJ.unregister(OpenCLProbeLibrary.class); } } if (debug) { String debugArgs = System.getenv(JAVACL_DEBUG_COMPILER_FLAGS_PROP); if (debugArgs != null) DEBUG_COMPILER_FLAGS = Arrays.asList(debugArgs.split(" ")); else if (Platform.isMacOSX()) DEBUG_COMPILER_FLAGS = Arrays.asList("-g"); else DEBUG_COMPILER_FLAGS = Arrays.asList("-O0", "-g"); int pid = ProcessUtils.getCurrentProcessId(); log( Level.INFO, "Debug mode enabled with compiler flags \"" + StringUtils.implode(DEBUG_COMPILER_FLAGS, " ") + "\" (can be overridden with env. var. JAVACL_DEBUG_COMPILER_FLAGS_PROP)"); log( Level.INFO, "You can debug your kernels with GDB using one of the following commands :\n" + "\tsudo gdb --tui --pid=" + pid + "\n" + "\tsudo ddd --debugger \"gdb --pid=" + pid + "\"\n" + "More info here :\n" + "\thttp://code.google.com/p/javacl/wiki/DebuggingKernels"); } CL = new OpenCLLibrary(); }
public boolean matches(Method method) { if (!symbol.contains(getMethodName(method))) { return false; } // if (!Modifier.isStatic(method.getModifiers()) && // !symbol.contains(method.getDeclaringClass().getSimpleName())) // return false; parse(); try { if (ref != null) { boolean res = ref.matches(method); if (!res && BridJ.debug) { BridJ.debug( "Symbol " + symbol + " was a good candidate but expected demangled signature " + ref + " did not match the method " + method); } return res; } } catch (Exception ex) { ex.printStackTrace(); } return false; }
public int getPositionInVirtualTable( Pointer<Pointer<?>> pVirtualTable, Method method, NativeLibrary library) { // Pointer<?> typeInfo = pVirtualTable.get(1); int methodsOffset = 0; // library.isMSVC() ? 0 : -2;///2; String className = getCPPClassName(method.getDeclaringClass()); for (int iVirtual = 0; ; iVirtual++) { Pointer<?> pMethod = pVirtualTable.get(methodsOffset + iVirtual); String virtualMethodName = pMethod == null ? null : library.getSymbolName(pMethod.getPeer()); // System.out.println("#\n# At index " + methodsOffset + " + " + iVirtual + " of vptr for // class " + className + ", found symbol " + Long.toHexString(pMethod.getPeer()) + " = '" + // virtualMethodName + "'\n#"); if (virtualMethodName == null) { if (debug) info("\tVtable(" + className + ")[" + iVirtual + "] = null"); return -1; } try { MemberRef mr = library.parseSymbol(virtualMethodName); if (debug) info("\tVtable(" + className + ")[" + iVirtual + "] = " + virtualMethodName + " = " + mr); if (mr != null && mr.matchesSignature(method)) return iVirtual; else if (library.isMSVC() && !mr.matchesEnclosingType(method)) break; // no NULL terminator in MSVC++ vtables, so we have to guess when we've reached the // end } catch (Demangler.DemanglingException ex) { BridJ.warning( "Failed to demangle '" + virtualMethodName + "' during inspection of virtual table for '" + method.toGenericString() + "' : " + ex); } } return -1; }
Pointer.Releaser newCPPReleaser(final Type type) { try { final Class<?> typeClass = Utils.getClass(type); NativeLibrary lib = BridJ.getNativeLibrary(typeClass); return newCPPReleaser(type, typeClass, lib); } catch (Throwable th) { throw new RuntimeException( "Failed to create a C++ destructor for type " + Utils.toString(type) + " : " + th, th); } }
@Override public T cast(Pointer peer) { if (BridJ.isCastingNativeObjectReturnTypeInCurrentThread()) { peer = peer.withReleaser(newCPPReleaser(type)); } T instance = super.cast(peer); Object[] templateParameters = getTemplateParameters(type); setTemplateParameters(instance, (Class) typeClass, templateParameters); return instance; }
// @Array(Toto.IBV_SYSFS_NAME_MAX.value) public static void print(String name, long addr, int n, int minI) { System.out.println(name); for (int i = -1; i < n; i++) { long v = getPtr(addr + i * Pointer.SIZE); Symbol sym = BridJ.getSymbolByAddress(v); String sname = sym == null ? null : sym.getName(); System.out.println("\tOffset " + i + ":\t" + hex(v) + " \t('" + sname + "')"); if (v == 0 && i >= minI) break; } System.out.println(); }
private Bundle getBundle(String bundleName) { Bundle bundle = bundles.get(bundleName); if (bundle == null) { /* NativeLibrary.addSearchPath(bundleName, "."); String module_path = System.getenv("GSP_MODULES_PATH"); if (module_path != null && !module_path.isEmpty()) { String delims = ":"; String[] tokens = module_path.split(delims); for (int i = 0; i < tokens.length; i++) { if(!tokens[i].isEmpty()) NativeLibrary.addSearchPath(bundleName, tokens[i]); } } module_path = System.getProperty("gsp.module.path"); if (module_path != null && !module_path.isEmpty()) { String delims = ":"; String[] tokens = module_path.split(delims); for (int i = 0; i < tokens.length; i++) { if(!tokens[i].isEmpty()) System.err.println("ADDED "+tokens[i]); NativeLibrary.addSearchPath(bundleName, tokens[i]); } } try { bundle = new Bundle(NativeLibrary.getInstance(bundleName), NativeFunctionFinder.create(bundleName)); bundles.put(bundleName, bundle); } catch (Exception e) { // TODO test NativeFunctionFinder also (add exceptions in it, or in the create or ...) // cannot load // TODO report }*/ try { bundle = new Bundle(BridJ.getNativeLibrary(bundleName), NativeFunctionFinder.create(bundleName)); bundles.put(bundleName, bundle); // bundle.jnalibrary = NativeLibrary.getInstance(bundleName); } catch (Exception e) { throw ex("Could not load native bundle/library with name '" + bundleName + "'", e); // TODO test NativeFunctionFinder also (add exceptions in it, or in the create or ...) // cannot load // TODO report } } return bundle; }
static int getArgumentsStackSize(Method method) { int total = 0; Type[] paramTypes = method.getGenericParameterTypes(); Annotation[][] anns = method.getParameterAnnotations(); for (int iArg = 0, nArgs = paramTypes.length; iArg < nArgs; iArg++) { Class<?> paramType = getTypeClass(paramTypes[iArg]); if (paramType == int.class) { total += 4; } else if (paramType == long.class) { Annotation[] as = anns[iArg]; if (isAnnotationPresent(Ptr.class, as) || isAnnotationPresent( org.bridj.ann.CLong.class, as)) // if (hasInstance(anns[iArg], Ptr.class, CLong.class)) { total += Pointer.SIZE; } else { total += 8; } } else if (paramType == float.class) { total += 4; } else if (paramType == double.class) { total += 8; } else if (paramType == byte.class) { total += 1; } else if (paramType == char.class) { total += Platform.WCHAR_T_SIZE; } else if (paramType == CLong.class) { total += Platform.CLONG_SIZE; } else if (paramType == SizeT.class) { total += Platform.SIZE_T_SIZE; } else if (paramType == TimeT.class) { total += Platform.TIME_T_SIZE; } else if (paramType == short.class) { total += 2; } else if (paramType == boolean.class) { total += 1; } else if (Pointer.class.isAssignableFrom(paramType)) { total += Pointer.SIZE; } else if (NativeObject.class.isAssignableFrom(paramType)) { total += ((CRuntime) BridJ.getRuntime(paramType)).sizeOf(paramTypes[iArg], null); } else if (FlagSet.class.isAssignableFrom(paramType)) { total += 4; // TODO } else { throw new RuntimeException("Type not handled : " + paramType.getName()); } } return total; }
synchronized void parse() { if (!refParsed) { try { ref = library.parseSymbol(symbol); } catch (DemanglingException ex) { if (BridJ.debug) { ex.printStackTrace(); } if (BridJ.verbose) { BridJ.warning("Symbol parsing failed : " + ex.getMessage()); } } refParsed = true; } }
protected boolean installRegularVTablePtr(Type type, NativeLibrary library, Pointer<?> peer) { long vtablePtr = getVirtualTable(type, library); if (vtablePtr != 0) { if (BridJ.debug) BridJ.info( "Installing regular vtable pointer " + Pointer.pointerToAddress(vtablePtr) + " to instance at " + peer + " (type = " + Utils.toString(type) + ")"); peer.setSizeT(vtablePtr); return true; } return false; }
private boolean matchesArgs(Type[] parameterTypes, Annotation[][] anns, int offset) { int totalArgs = offset; for (int i = 0, n = templateArguments == null ? 0 : templateArguments.length; i < n; i++) { if (totalArgs >= parameterTypes.length) { return false; } Type paramType = parameterTypes[offset + i]; TemplateArg arg = templateArguments[i]; if (arg instanceof TypeRef) { if (!paramType.equals(Class.class)) { return false; } } else if (arg instanceof Constant) { try { getTypeClass(paramType).cast(((Constant) arg).value); } catch (ClassCastException ex) { return false; } } totalArgs++; } for (int i = 0, n = paramTypes == null ? 0 : paramTypes.length; i < n; i++) { if (totalArgs >= parameterTypes.length) { return false; } TypeRef paramType = paramTypes[i]; Type parameterType = parameterTypes[totalArgs]; if (!paramType.matches(parameterType, annotations(anns == null ? null : anns[i]))) { return false; } totalArgs++; } if (totalArgs != parameterTypes.length) { BridJ.error("Not enough args for " + this); return false; } return true; }
protected VTable synthetizeVirtualTable( Type type, Pointer<Pointer> parentVTablePtr, List<VirtMeth> methods, NativeLibrary library) { int nMethods = methods.size(); // Pointer<Pointer> parentVTablePtr = pointerToAddress(getVirtualTable(Utils.getParent(type), // library), Pointer.class); VTable vtable = new VTable(); vtable.ptr = allocatePointers(nMethods + 2) .next( 2); // leave two null pointers at index -2 and -1, to say there's no runtime type // information available. Class<?> c = Utils.getClass(type); for (int iMethod = 0; iMethod < nMethods; iMethod++) { VirtMeth vm = methods.get(iMethod); Pointer<?> pMethod; if (Modifier.isNative(vm.implementation.getModifiers())) { pMethod = parentVTablePtr == null ? null : parentVTablePtr.get(iMethod); } else { try { MethodCallInfo mci = new MethodCallInfo(vm.implementation, vm.definition); mci.setDeclaringClass(vm.implementation.getDeclaringClass()); pMethod = createCToJavaCallback(mci, c); vtable.callbacks.put(vm.implementation, pMethod); } catch (Throwable th) { BridJ.error( "Failed to register overridden method " + vm.implementation + " for type " + type + " (original method = " + vm.definition + ")", th); pMethod = null; } } vtable.ptr.set(iMethod, (Pointer) pMethod); } return vtable; }
static { BridJ.setNativeLibraryActualName("OpenCLProbe", "OpenCL"); BridJ.register(); }
static { BridJ.register(); }
/** * It provides access to the native avformat library. The methods' documentation has been taken from * the original Libav documentation. * * @author Ondrej Perutka */ public final class AVResampleLibrary implements ILibrary { public static final String LIB_NAME = BridJ.getNativeLibraryName(Lib.class); public static final int MIN_MAJOR_VERSION = 0; public static final int MAX_MAJOR_VERSION = 1; private int majorVersion; private int minorVersion; private int microVersion; private NativeLibrary lib; public AVResampleLibrary() throws IOException { lib = BridJ.getNativeLibrary(Lib.class); int libVersion = avresample_version(); majorVersion = (libVersion >> 16) & 0xff; minorVersion = (libVersion >> 8) & 0xff; microVersion = libVersion & 0xff; String version = String.format("%d.%d.%d", majorVersion, minorVersion, microVersion); File libFile = BridJ.getNativeLibraryFile(LIB_NAME); Logger.getLogger(getClass().getName()) .log( Level.INFO, "Loading {0} library, version {1}...", new Object[] {libFile.getAbsolutePath(), version}); if (majorVersion < MIN_MAJOR_VERSION || majorVersion > MAX_MAJOR_VERSION) throw new UnsatisfiedLinkError( "Unsupported version of the " + LIB_NAME + " native library. (" + MIN_MAJOR_VERSION + ".x.x <= required <= " + MAX_MAJOR_VERSION + ".x.x, found " + version + ")"); } @Override public boolean functionExists(String functionName) { return lib.getSymbol(functionName) != null; } @Override public int getMajorVersion() { return majorVersion; } @Override public int getMicroVersion() { return microVersion; } @Override public int getMinorVersion() { return minorVersion; } /** * Get version of the avresample library. Bits 23 to 16 represents major version, bits 15 to 8 are * for minor version and bits 7 to 0 are for micro version. * * @return version of the avresample library */ public int avresample_version() { return Lib.avresample_version(); } /** * Allocate AVAudioResampleContext and set options. * * @return allocated audio resample context, or null on failure */ public Pointer<?> avresample_alloc_context() { return Lib.avresample_alloc_context(); } /** * Initialize AVAudioResampleContext. * * @param avr audio resample context * @return 0 on success, negative AVERROR code on failure */ public int avresample_open(Pointer<?> avr) { return Lib.avresample_open(avr); } /** * Close AVAudioResampleContext. * * <p>This closes the context, but it does not change the parameters. The context can be reopened * with avresample_open(). It does, however, clear the output FIFO and any remaining leftover * samples in the resampling delay buffer. If there was a custom matrix being used, that is also * cleared. * * @param avr audio resample context */ public void avresample_close(Pointer<?> avr) { Lib.avresample_close(avr); } /** * Free AVAudioResampleContext and associated AVOption values. * * <p>This also calls avresample_close() before freeing. * * @param avr audio resample context */ public void avresample_free(Pointer<Pointer<?>> avr) { Lib.avresample_free(avr); } /** * Get the current channel mixing matrix. * * @param avr audio resample context * @param matrix mixing coefficients; matrix[i + stride * o] is the weight of input channel i in * output channel o. * @param stride distance between adjacent input channels in the matrix array * @return 0 on success, negative AVERROR code on failure */ public int avresample_get_matrix(Pointer<?> avr, Pointer<Double> matrix, int stride) { return Lib.avresample_get_matrix(avr, matrix, stride); } /** * Set channel mixing matrix. * * <p>Allows for setting a custom mixing matrix, overriding the default matrix generated * internally during avresample_open(). This function can be called anytime on an allocated * context, either before or after calling avresample_open(). avresample_convert() always uses the * current matrix. Calling avresample_close() on the context will clear the current matrix. * * @param avr audio resample context * @param matrix mixing coefficients; matrix[i + stride * o] is the weight of input channel i in * output channel o. * @param stride distance between adjacent input channels in the matrix array * @return 0 on success, negative AVERROR code on failure */ public int avresample_set_matrix(Pointer<?> avr, Pointer<Double> matrix, int stride) { return Lib.avresample_set_matrix(avr, matrix, stride); } /** * Convert input samples and write them to the output FIFO. * * <p>The output data can be NULL or have fewer allocated samples than required. In this case, any * remaining samples not written to the output will be added to an internal FIFO buffer, to be * returned at the next call to this function or to avresample_read(). * * <p>If converting sample rate, there may be data remaining in the internal resampling delay * buffer. avresample_get_delay() tells the number of remaining samples. To get this data as * output, call avresample_convert() with NULL input. * * <p>At the end of the conversion process, there may be data remaining in the internal FIFO * buffer. avresample_available() tells the number of remaining samples. To get this data as * output, either call avresample_convert() with NULL input or call avresample_read(). * * @param avr audio resample context * @param output output data pointers * @param out_plane_size output plane size, in bytes. This can be 0 if unknown, but that will lead * to optimized functions not being used directly on the output, which could slow down some * conversions. * @param out_samples maximum number of samples that the output buffer can hold * @param input input data pointers * @param in_plane_size input plane size, in bytes This can be 0 if unknown, but that will lead to * optimized functions not being used directly on the input, which could slow down some * conversions. * @param in_samples number of input samples to convert * @return number of samples written to the output buffer, not including converted samples added * to the internal output FIFO */ public int avresample_convert( Pointer<?> avr, Pointer<Pointer<?>> output, int out_plane_size, int out_samples, Pointer<Pointer<?>> input, int in_plane_size, int in_samples) { return Lib.avresample_convert( avr, output, out_plane_size, out_samples, input, in_plane_size, in_samples); } @Library("avresample") private static class Lib { static { BridJ.register(); } public static native int avresample_version(); public static native Pointer<?> avresample_alloc_context(); public static native int avresample_open(Pointer<?> avr); public static native void avresample_close(Pointer<?> avr); public static native void avresample_free(Pointer<Pointer<?>> avr); public static native int avresample_get_matrix( Pointer<?> avr, Pointer<Double> matrix, int stride); public static native int avresample_set_matrix( Pointer<?> avr, Pointer<Double> matrix, int stride); public static native int avresample_convert( Pointer<?> avr, Pointer<Pointer<?>> output, int out_plane_size, int out_samples, Pointer<Pointer<?>> input, int in_plane_size, int in_samples); } }
public static CPPRuntime getInstance() { return BridJ.getRuntimeByRuntimeClass(CPPRuntime.class); }
static { BridJ.register(); // Ctest.class); }
public static void main(String[] args) throws IOException { try { { JFrame f = new JFrame(); f.setVisible(true); long hwndVal = JAWTUtils.getNativePeerHandle(f); // TODO com.sun.jna.Native.getComponentID(this); System.out.println("#\n# hwndVal = " + hwndVal + "\n#"); BridJ.register(); ValuedEnum<ETest> t = testEnum(ETest.eFirst); if (t != ETest.eFirst) throw new RuntimeException(); } testSetGetIntBuffer(10); // if (Platform.isMacOSX()) { // new NSCalendar(); // new NSAutoReleasePool(); // } // NativeLibrary lib = BridJ.getNativeLibrary("OpenCL", new // File("/System/Library/Frameworks/OpenCL.framework/OpenCL")); // NativeLibrary lib = BridJ.getNativeLibrary("OpenCL", new // File("/usr/lib/libobjc.dylib")); // NativeLibrary lib = BridJ.getNativeLibrary("OpenCL", new // File("/Users/ochafik/nativelibs4java/Runtime/BridJ/src/test/cpp/test/build_out/darwin_universal_gcc_debug/libtest.dylib")); // Collection<Symbol> symbols = lib.getSymbols(); BridJ.register(MyCallback.class); BridJ.register(); int ra = testAddDyncall(10, 4); if (ra != 14) throw new RuntimeException("Expected 14, got " + ra); ra = testAddDyncall(10, 4); if (ra != 14) throw new RuntimeException("Expected 14, got " + ra); testNativeTargetCallbacks(); testJavaTargetCallbacks(); if (true) return; long crea = Ctest.createTest(); crea = Pointer.pointerToAddress(crea).getPointer().getPeer(); print("Ctest.createTest()", crea, 10, 0); Ctest test = new Ctest(); // long thisPtr = test.$this.getPeer(); // System.out.println(hex(thisPtr)); print("Ctest.this", Pointer.pointerTo(test, Ctest.class).getPointer().getPeer(), 10, 2); int res = test.testAdd(1, 2); System.out.println("res = " + res); res = test.testVirtualAdd(1, 2); System.out.println("res = " + res); res = test.testVirtualAddStdCall(null, 1, 2); System.out.println("res = " + res); res = test.testAddStdCall(null, 1, 2); System.out.println("res = " + res); TaskbarListDemo.main(null); IShellWindows win = COMRuntime.newInstance(IShellWindows.class); IUnknown iu = win.QueryInterface(IUnknown.class); if (iu == null) throw new RuntimeException("Interface does not handle IUnknown !"); win.Release(); try { new FunctionTest().add(); MyStruct s = new MyStruct(); s.a(10); System.out.println("Created MyStruct and set it to 10"); int a = Pointer.pointerTo(s).getInt(); a = s.a(); Pointer.pointerTo(s).setInt(10); a = Pointer.pointerTo(s).getInt(); a = s.a(); if (s.a() != 10) throw new RuntimeException("invalid value = " + a); s.b(100.0); if (s.b() != 100.0) throw new RuntimeException("invalid value = " + a); } catch (Throwable ex) { ex.printStackTrace(); } library = BridJ.getNativeLibrary("test"); // NativeLibrary.load(libraryPath); new VC9Demangler(null, "?sinInt@@YANH@Z").parseSymbol(); new VC9Demangler(null, "?forwardCall@@YAHP6AHHH@ZHH@Z").parseSymbol(); BridJ.register(); // new VC9Demangler(null, "??0Ctest2@@QEAA@XZ").parseSymbol(); for (Demangler.Symbol symbol : library.getSymbols()) { String name = symbol.getName(); long addr = symbol.getAddress(); System.out.println(name + " = \t" + hex(addr)); if (name.startsWith("_ZTV") || name.startsWith("_ZTI") || name.startsWith("??_")) { print("vtable", addr, 10, 1); } else System.out.println("'" + name + "'"); } boolean is64 = Platform.is64Bits(); } catch (Throwable ex) { ex.printStackTrace(); } finally { System.in.read(); } /*double dres = PerfLib.testASinB(1, 2); res = PerfLib.testAddJNI(1, 2); System.out.println("Done");*/ }
DynamicFunction getConstructor( final Class<?> typeClass, final Type type, NativeLibrary lib, int constructorId) { Pair<Type, Integer> key = new Pair<Type, Integer>(type, constructorId); DynamicFunction constructor = constructors.get(key); if (constructor == null) { try { final Constructor<?> constr; try { constr = findConstructor(typeClass, constructorId, true); if (debug) BridJ.info("Found constructor for " + Utils.toString(type) + " : " + constr); } catch (NoSuchMethodException ex) { if (debug) BridJ.info("No constructor for " + Utils.toString(type)); return null; } Symbol symbol = lib == null ? null : lib.getFirstMatchingSymbol( new SymbolAccepter() { public boolean accept(Symbol symbol) { return symbol.matchesConstructor( constr.getDeclaringClass() == Utils.getClass(type) ? type : constr.getDeclaringClass() /* TODO */, constr); } }); if (symbol == null) { if (debug) BridJ.info("No matching constructor for " + Utils.toString(type) + " (" + constr + ")"); return null; } if (debug) info("Registering constructor " + constr + " as " + symbol.getName()); // TODO do something with these args ! int templateParametersCount = getTemplateParametersCount(typeClass); Class<?>[] consParamTypes = constr.getParameterTypes(); Class<?>[] consThisParamTypes = new Class[consParamTypes.length + 1 - templateParametersCount]; consThisParamTypes[0] = Pointer.class; System.arraycopy( consParamTypes, templateParametersCount, consThisParamTypes, 1, consParamTypes.length - templateParametersCount); DynamicFunctionFactory constructorFactory = getDynamicFunctionFactory(lib, Style.ThisCall, void.class, consThisParamTypes); constructor = constructorFactory.newInstance(pointerToAddress(symbol.getAddress())); constructors.put(key, constructor); } catch (Throwable th) { th.printStackTrace(); throw new RuntimeException( "Unable to create constructor " + constructorId + " for " + type + " : " + th, th); } } return constructor; }
public FunctionTest() { BridJ.register(getClass()); }