當前位置: 首頁>>代碼示例>>Java>>正文


Java Native類代碼示例

本文整理匯總了Java中com.sun.jna.Native的典型用法代碼示例。如果您正苦於以下問題:Java Native類的具體用法?Java Native怎麽用?Java Native使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Native類屬於com.sun.jna包,在下文中一共展示了Native類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: CLibrary

import com.sun.jna.Native; //導入依賴的package包/類
public CLibrary() {
switch (Platform.get()) {
    case LinuxIntel32:
    case LinuxIntel64:
	delegate = (GenericCLibrary) Native.loadLibrary("c", DefaultCLibrary.class);
	constants = new LinuxConstants();
	break;
    case MacosIntel32:
	delegate = (GenericCLibrary) Native.loadLibrary("c", DefaultCLibrary.class);
	constants = new MacConstants();
	break;
    case SolarisIntel32:
    case SolarisIntel64:
    case SolarisSparc32:
    case SolarisSparc64:
	delegate = (GenericCLibrary) Native.loadLibrary("c", DefaultCLibrary.class);
	constants = new SolarisConstants();
	break;
    case WindowsIntel32:
    case Other:
    default:
	delegate = (GenericCLibrary) Native.loadLibrary("c", DefaultCLibrary.class);
	constants = new DefaultConstants();
	break;
}
   }
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:27,代碼來源:CLibrary.java

示例2: getDiskSize

import com.sun.jna.Native; //導入依賴的package包/類
private long getDiskSize(Disk disk) {
    long result = -1l;
    Kernel32 kernel32 = Kernel32.INSTANCE;
    HANDLE diskHandle = kernel32.CreateFile(disk.path, WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, null,
            WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null);
    if (WinBase.INVALID_HANDLE_VALUE.equals(diskHandle)) {
        return result;
    }
    try {
        Memory output = new Memory(Native.getNativeSize(LARGE_INTEGER.class));
        IntByReference lpBytes = new IntByReference();
        boolean success = kernel32.DeviceIoControl(diskHandle,
                WinioctlUtil.CTL_CODE(Winioctl.FILE_DEVICE_DISK, 0x17, Winioctl.METHOD_BUFFERED,
                        Winioctl.FILE_READ_ACCESS),
                null, 0, output, Native.getNativeSize(LARGE_INTEGER.class), lpBytes, null);
        // TODO: Check success?
        result = output.getLong(0);
    }
    finally {
        Kernel32Util.closeHandle(diskHandle);
    }
    return result;
}
 
開發者ID:ciphertechsolutions,項目名稱:IO,代碼行數:24,代碼來源:DeviceManager.java

示例3: while

import com.sun.jna.Native; //導入依賴的package包/類
/**
 * Finds the given process in the process list.
 *
 * @param processEntry The process entry.
 * @param filenamePattern pattern matching the filename of the process.
 * @return The found process entry.
 */
public static boolean findProcessEntry
                (final Tlhelp32.PROCESSENTRY32.ByReference processEntry,
                 final Pattern filenamePattern) {
    Kernel32 kernel32 = Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);

    WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));

    boolean found = false;

    try {
        while (kernel32.Process32Next(snapshot, processEntry)) {
            String fname = Native.toString(processEntry.szExeFile);

            if (fname != null && filenamePattern.matcher(fname).matches()) {
                found = true;
                break;
            }
        }
    } finally {
        kernel32.CloseHandle(snapshot);
    }

    return found;
}
 
開發者ID:mmarquee,項目名稱:ui-automation,代碼行數:32,代碼來源:Utils.java

示例4: openServiceControlManager

import com.sun.jna.Native; //導入依賴的package包/類
/**
 * Get a handle to the ServiceControlManager.
 * 
 * @param machine
 *            name of the machine or null for localhost
 * @param access
 *            access flags
 * @return handle to ServiceControlManager or null when failed
 */
static private SC_HANDLE openServiceControlManager(String machine, int access)
{
	SC_HANDLE handle = null;
	Advapi32 advapi32;

	advapi32 = Advapi32.INSTANCE;
	handle = advapi32.OpenSCManager(machine, null, access);
	if (handle == null)
	{
		int err = Native.getLastError();
		lastWinError = err;
		System.out.println("Error in OpenSCManager: " + Integer.toHexString(err));
		if (err == 5)
			System.out.println("Access denied: please check the user credentials");
	}

	return (handle);
}
 
開發者ID:yajsw,項目名稱:yajsw,代碼行數:28,代碼來源:Win32Service.java

示例5: free

import com.sun.jna.Native; //導入依賴的package包/類
public static void free(long peer)
{
    long sizeInBytes = memTracker.get(peer);
    long totalSizeInBytes = ALLOCATED_SIZE.addAndGet(-1 * sizeInBytes);

    if (totalSizeInBytes < 0) {
        ALLOCATED_SIZE.set(0);
        totalSizeInBytes = 0;
    }

    LOGGER.info("Freeing off-heap memory block of " + (sizeInBytes/1048576) +
            "Mb and total allocated off-heap memory size is " + (totalSizeInBytes/1048576) + "Mb");
    Native.free(peer);
    memTracker.remove(peer);

}
 
開發者ID:Netflix,項目名稱:sstable-adaptor,代碼行數:17,代碼來源:MemoryUtil.java

示例6: makeRaw

import com.sun.jna.Native; //導入依賴的package包/類
/**
 * Make out own i/o be raw.
 */
private static void makeRaw() {
    String ttyName = "/dev/tty";
    int ofd = Util.getFd(FileDescriptor.out);

    CLibrary.LinuxTermios termios = new CLibrary.LinuxTermios();

    // check existing settings
    // If we don't do this tcssetattr() will return EINVAL.
    if (CLibrary.INSTANCE.tcgetattr(ofd, termios) == -1) {
        error("tcgetattr(\"" + ttyName + "\", <termios>) failed -- " + strerror(Native.getLastError()));
    }

    // System.out.printf("tcgetattr() gives %s\r\n", termios);

    // initialize values relevant for raw mode
    CLibrary.INSTANCE.cfmakeraw(termios);

    // System.out.printf("cfmakeraw() gives %s\r\n", termios);

    // apply them
    if (CLibrary.INSTANCE.tcsetattr(ofd, CLibrary.INSTANCE.TCSANOW(), termios) == -1) {
        error("tcsetattr(\"" + ttyName + "\", TCSANOW, <termios>) failed -- " + strerror(Native.getLastError()));
    }
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:28,代碼來源:Main.java

示例7: getHostname

import com.sun.jna.Native; //導入依賴的package包/類
/**
 * @return the hostname the of the current machine
 */
public static String getHostname() {
    if (Platform.isWindows()) {
        return Kernel32Util.getComputerName();
    } else {
        // For now, we'll consider anyhting other than Windows to be unix-ish enough to have gethostname
        // TODO - Consider http://stackoverflow.com/a/10543006 as a possibly better MacOS option
        
        byte[] hostnameBuffer = new byte[4097];
        // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html suggests
        // the actual limit would be 255.
        
        int result = UnixCLibrary.INSTANCE.gethostname(hostnameBuffer, hostnameBuffer.length);
        if (result != 0) {
            throw new RuntimeException("gethostname call failed");
        }
        
        return Native.toString(hostnameBuffer);
    }
}
 
開發者ID:mattsheppard,項目名稱:gethostname4j,代碼行數:23,代碼來源:Hostname.java

示例8: trySetMaxNumberOfThreads

import com.sun.jna.Native; //導入依賴的package包/類
static void trySetMaxNumberOfThreads() {
    if (Constants.LINUX) {
        // this is only valid on Linux and the value *is* different on OS X
        // see /usr/include/sys/resource.h on OS X
        // on Linux the resource RLIMIT_NPROC means *the number of threads*
        // this is in opposition to BSD-derived OSes
        final int rlimit_nproc = 6;

        final JNACLibrary.Rlimit rlimit = new JNACLibrary.Rlimit();
        if (JNACLibrary.getrlimit(rlimit_nproc, rlimit) == 0) {
            MAX_NUMBER_OF_THREADS = rlimit.rlim_cur.longValue();
        } else {
            logger.warn("unable to retrieve max number of threads [" + JNACLibrary.strerror(Native.getLastError()) + "]");
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:17,代碼來源:JNANatives.java

示例9: solarisImpl

import com.sun.jna.Native; //導入依賴的package包/類
static void solarisImpl() {
    // first be defensive: we can give nice errors this way, at the very least.
    boolean supported = Constants.SUN_OS;
    if (supported == false) {
        throw new IllegalStateException("bug: should not be trying to initialize priv_set for an unsupported OS");
    }

    // we couldn't link methods, could be some really ancient Solaris or some bug
    if (libc_solaris == null) {
        throw new UnsupportedOperationException("priv_set unavailable: could not link methods. requires Solaris 10+");
    }

    // drop a null-terminated list of privileges
    if (libc_solaris.priv_set(PRIV_OFF, PRIV_ALLSETS, PRIV_PROC_FORK, PRIV_PROC_EXEC, null) != 0) {
        throw new UnsupportedOperationException("priv_set unavailable: priv_set(): " + JNACLibrary.strerror(Native.getLastError()));
    }

    logger.debug("Solaris priv_set initialization successful");
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:SystemCallFilter.java

示例10: validate

import com.sun.jna.Native; //導入依賴的package包/類
/**
 * Validates if the expression instance is valid
 * @return ValidationResult object
 */


public ValidationResult validate() {
    PointerByReference info = new PointerByReference();
    PointerByReference error = new PointerByReference();

    int hsResult = HyperscanLibrary.INSTANCE.hs_expression_info(this.expression, Util.bitEnumSetToInt(this.flags), info, error);

    String errorMessage = "";
    boolean isValid = true;

    if(hsResult != 0) {
        isValid = false;
        CompileErrorStruct errorStruct = new CompileErrorStruct(error.getValue());
        errorMessage = errorStruct.message;
        errorStruct.setAutoRead(false);
        HyperscanLibrary.INSTANCE.hs_free_compile_error(errorStruct);
    }
    else {
        Native.free(Pointer.nativeValue(info.getValue()));
    }

    return new ValidationResult(errorMessage, isValid);
}
 
開發者ID:cerebuild,項目名稱:hyperscan-java,代碼行數:29,代碼來源:Expression.java

示例11: OdsDll

import com.sun.jna.Native; //導入依賴的package包/類
public OdsDll(String nativeDllPath) {

		if (dllYetToBeInitialized) {

			String actualNativeDllPath = "ods";
			if (nativeDllPath != null) {
				File nativeDllFileOrDir = new File(nativeDllPath);
				if (!nativeDllFileOrDir.exists()) {
					throw new RuntimeException("Invalid native DLL path: " + nativeDllFileOrDir.getAbsolutePath());
				}
				if (nativeDllFileOrDir.isDirectory()) {
					actualNativeDllPath = nativeDllPath + "/ods";
				} else {
					actualNativeDllPath = nativeDllPath;
					for (String ext : new String[]{ ".so", ".dll" }) {
						if (actualNativeDllPath.toLowerCase().endsWith(ext))
							actualNativeDllPath = actualNativeDllPath.substring(
									0, actualNativeDllPath.length() - ext.length());
					}
				}
			}

			// Delft3D-Flow uses ifort for both linux and windows.
			// If in the future another compiler is needed, e.g. gfortran,
			// see org.openda.model_efdc_dll.EfdcDLL for an example of function name mapping.
			if(BBUtils.RUNNING_ON_WINDOWS){
				odsWinIfortDll = (OdsWinIfortDll) Native.loadLibrary(actualNativeDllPath, OdsWinIfortDll.class);

			}else{
				// GfortranFunctionMapper gFortranMapper = new GfortranFunctionMapper();
				// HashMap<String, String> gFortranMap = gFortranMapper.getMap();
				odsWinIfortDll = (OdsWinIfortDll) Native.loadLibrary(
						actualNativeDllPath, OdsWinIfortDll.class); // , gFortranMap);
			}
			dllYetToBeInitialized = true;
		}
	}
 
開發者ID:OpenDA-Association,項目名稱:OpenDA,代碼行數:38,代碼來源:OdsDll.java

示例12: solarisImpl

import com.sun.jna.Native; //導入依賴的package包/類
static void solarisImpl() {
    // first be defensive: we can give nice errors this way, at the very least.
    boolean supported = Constants.SUN_OS;
    if (supported == false) {
        throw new IllegalStateException("bug: should not be trying to initialize priv_set for an unsupported OS");
    }

    // we couldn't link methods, could be some really ancient Solaris or some bug
    if (libc_solaris == null) {
        throw new UnsupportedOperationException("priv_set unavailable: could not link methods. requires Solaris 10+");
    }

    // drop a null-terminated list of privileges 
    if (libc_solaris.priv_set(PRIV_OFF, PRIV_ALLSETS, PRIV_PROC_FORK, PRIV_PROC_EXEC, null) != 0) {
        throw new UnsupportedOperationException("priv_set unavailable: priv_set(): " + JNACLibrary.strerror(Native.getLastError()));
    }

    logger.debug("Solaris priv_set initialization successful");
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:20,代碼來源:Seccomp.java

示例13: lockMemory

import com.sun.jna.Native; //導入依賴的package包/類
public static void lockMemory() {
  int result = 0;
  try {
    Native.register(Platform.C_LIBRARY_NAME);
    result = mlockall(1);
    if (result == 0) {
      return;
    }
  } catch (Throwable t) {
    throw new IllegalStateException("Error trying to lock memory", t);
  }

  int errno = Native.getLastError();
  String msg = "mlockall failed: " + errno;
  if (errno == 1 || errno == 12) { // EPERM || ENOMEM
    msg = "Unable to lock memory due to insufficient free space or privileges.  "
        + "Please check the RLIMIT_MEMLOCK soft resource limit (ulimit -l) and "
        + "increase the available memory if needed";
  }
  throw new IllegalStateException(msg);
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:22,代碼來源:GemFireCacheImpl.java

示例14: start

import com.sun.jna.Native; //導入依賴的package包/類
public static synchronized void start(HackRFSweepDataCallback dataCallback, int freq_min_MHz, int freq_max_MHz, int fft_bin_width, int num_samples,
		int lna_gain, int vga_gain, boolean antennaPowerEnable)
{
	hackrf_sweep_lib_start__fft_power_callback_callback callback = new hackrf_sweep_lib_start__fft_power_callback_callback()
	{
		@Override public void apply(byte sweep_started, int bins, DoubleByReference freqStart, float fftBinWidth, FloatByReference powerdBm)
		{
			double[] freqStartArr = bins == 0 ? null : freqStart.getPointer().getDoubleArray(0, bins);
			float[] powerArr =  bins == 0 ? null : powerdBm.getPointer().getFloatArray(0, bins);
			dataCallback.newSpectrumData(sweep_started==0 ? false : true, freqStartArr, fftBinWidth, powerArr);
		}
	};
	Native.setCallbackThreadInitializer(callback, new CallbackThreadInitializer(true));

	HackrfSweepLibrary.hackrf_sweep_lib_start(callback, freq_min_MHz, freq_max_MHz, fft_bin_width, num_samples, lna_gain, vga_gain, antennaPowerEnable ? 1 : 0);
}
 
開發者ID:pavsa,項目名稱:hackrf-spectrum-analyzer,代碼行數:17,代碼來源:HackRFSweepNativeBridge.java

示例15: main

import com.sun.jna.Native; //導入依賴的package包/類
public static void main(String[] args) {
    final User32 user32 = User32.INSTANCE;

    user32.EnumWindows(new User32.WNDENUMPROC() {

        int count;

        public boolean callback(Pointer hWnd, Pointer userData) {
            byte[] windowText = new byte[512];
            user32.GetWindowTextA(hWnd, windowText, 512);
            String wText = Native.toString(windowText);
            wText = (wText.isEmpty()) ? "" : "; text: " + wText;
            System.out.println("Found window " + hWnd + ", total " + ++count + wText);
            return true;
        }
    }, null);
}
 
開發者ID:symphonicon,項目名稱:Fav-Track,代碼行數:18,代碼來源:JNAMain.java


注:本文中的com.sun.jna.Native類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。