当前位置: 首页>>代码示例>>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;未经允许,请勿转载。