本文整理了Java中com.sun.jna.Native
类的一些代码示例,展示了Native
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Native
类的具体详情如下:
包路径:com.sun.jna.Native
类名称:Native
[英]Provides generation of invocation plumbing for a defined native library interface. Also provides various utilities for native operations.
#getTypeMapper and #getStructureAlignment are provided to avoid having to explicitly pass these parameters to Structures, which would require every Structure which requires custom mapping or alignment to define a constructor and pass parameters to the superclass. To avoid lots of boilerplate, the base Structure constructor figures out these properties based on its enclosing interface.
Library Loading When JNA classes are loaded, the native shared library (jnidispatch) is loaded as well. An attempt is made to load it from the system library path using System#loadLibrary. If not found, the appropriate library will be extracted from the class path into a temporary directory and loaded from there. If your system has additional security constraints regarding execution or load of files (SELinux, for example), you should probably install the native library in an accessible location and configure your system accordingly, rather than relying on JNA to extract the library from its own jar file.
[中]为定义的本机库接口提供调用管道的生成。还为本机操作提供各种实用程序。
#提供getTypeMapper和#GetStructureAllignment是为了避免必须显式地将这些参数传递给结构,这将要求每个需要自定义映射或对齐的结构定义构造函数并将参数传递给超类。为了避免大量样板文件,基本结构构造函数根据其封闭接口计算出这些属性。
库加载加载JNA类时,也会加载本机共享库(JNIDSPATCH)。尝试使用system#loadLibrary从系统库路径加载它。如果找不到,相应的库将从类路径提取到临时目录中,并从那里加载。如果您的系统在文件的执行或加载方面有额外的安全限制(例如SELinux),您可能应该将本机库安装在一个可访问的位置,并相应地配置您的系统,而不是依赖JNA从自己的jar文件中提取库。
代码示例来源:origin: languagetool-org/languagetool
protected void tryLoad(String libFile) throws UnsupportedOperationException {
hsl = (HunspellLibrary)Native.loadLibrary(libFile, HunspellLibrary.class);
}
代码示例来源:origin: jenkinsci/jenkins
IntByReference ref = new IntByReference(sizeOfInt);
IntByReference size = new IntByReference(sizeOfInt);
Memory m;
int nRetry = 0;
throw new IOException("Failed to obtain memory requirement: "+LIBC.strerror(Native.getLastError()));
m = new Memory(size.getValue());
if(LIBC.sysctl(MIB_PROC_ALL,3, m, size, NULL, ref)!=0) {
if(Native.getLastError()==ENOMEM && nRetry++<16)
continue; // retry
throw new IOException("Failed to call kern.proc.all: "+LIBC.strerror(Native.getLastError()));
for( int base=0; base<size.getValue(); base+=sizeOf_kinfo_proc) {
int pid = m.getInt(base+ kinfo_proc_pid_offset);
int ppid = m.getInt(base+ kinfo_proc_ppid_offset);
代码示例来源:origin: kaitoy/pcap4j
@Override
public String toString() {
return Native.toString(buf);
}
}
代码示例来源:origin: apache/geode
public static void lockMemory() {
try {
Native.register(Platform.C_LIBRARY_NAME);
int result = mlockall(1);
if (result == 0) {
return;
}
} catch (Throwable t) {
throw new IllegalStateException("Error trying to lock memory", t);
}
int lastError = Native.getLastError();
String message = "mlockall failed: " + lastError;
if (lastError == 1 || lastError == 12) { // EPERM || ENOMEM
message = "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(message);
}
代码示例来源:origin: jMonkeyEngine/jmonkeyengine
/**
* Init the native binding to the underlying system library.
* @return <code>true</code> if the link is effective and <code>false</code> otherwise.
*/
public static void init() throws UnsatisfiedLinkError {
Native.unregister(JOpenVRLibrary.class);
String path = System.getProperty(JNA_OPENVR_LIBRARY_PATH);
if (path != null){
JNA_LIBRARY_NAME = path;
logger.config("Using OpenVR implementation located at "+JNA_LIBRARY_NAME);
JNA_NATIVE_LIB = NativeLibrary.getInstance(JOpenVRLibrary.JNA_LIBRARY_NAME);
Native.register(JOpenVRLibrary.class, JOpenVRLibrary.JNA_NATIVE_LIB);
} else {
JNA_LIBRARY_NAME = "openvr_api";
logger.config("Using embedded OpenVR implementation "+JOpenVRLibrary.JNA_LIBRARY_NAME);
JNA_NATIVE_LIB = NativeLibrary.getInstance(JOpenVRLibrary.JNA_LIBRARY_NAME);
Native.register(JOpenVRLibrary.class, JOpenVRLibrary.JNA_NATIVE_LIB);
}
}
代码示例来源:origin: net.java.dev.jna/jna
/**
* When called from a class static initializer, maps all native methods
* found within that class to native libraries via the JNA raw calling
* interface.
* @param lib native library to which functions should be bound
*/
public static void register(NativeLibrary lib) {
register(findDirectMappedClass(getCallingClass()), lib);
}
代码示例来源:origin: org.elasticsearch/elasticsearch
private JNAKernel32Library() {
if (Constants.WINDOWS) {
try {
Native.register("kernel32");
logger.debug("windows/Kernel32 library loaded");
} catch (NoClassDefFoundError e) {
logger.warn("JNA not found. native methods and handlers will be disabled.");
} catch (UnsatisfiedLinkError e) {
logger.warn("unable to link Windows/Kernel32 library. native methods and handlers will be disabled.");
}
}
}
代码示例来源:origin: org.elasticsearch/elasticsearch
static void trySetMaxFileSize() {
if (Constants.LINUX || Constants.MAC_OS_X) {
final JNACLibrary.Rlimit rlimit = new JNACLibrary.Rlimit();
if (JNACLibrary.getrlimit(JNACLibrary.RLIMIT_FSIZE, rlimit) == 0) {
MAX_FILE_SIZE = rlimit.rlim_cur.longValue();
} else {
logger.warn("unable to retrieve max file size [" + JNACLibrary.strerror(Native.getLastError()) + "]");
}
}
}
代码示例来源:origin: org.elasticsearch/elasticsearch
static void addConsoleCtrlHandler(ConsoleCtrlHandler handler) {
// The console Ctrl handler is necessary on Windows platforms only.
if (Constants.WINDOWS) {
try {
boolean result = JNAKernel32Library.getInstance().addConsoleCtrlHandler(handler);
if (result) {
logger.debug("console ctrl handler correctly set");
} else {
logger.warn("unknown error {} when adding console ctrl handler", Native.getLastError());
}
} catch (UnsatisfiedLinkError e) {
// this will have already been logged by Kernel32Library, no need to repeat it
}
}
}
代码示例来源:origin: org.elasticsearch/elasticsearch
throw new UnsupportedOperationException("seccomp unavailable: seccomp(BOGUS_OPERATION) returned " + ret);
} else {
int errno = Native.getLastError();
switch (errno) {
case ENOSYS: break; // ok
throw new UnsupportedOperationException("seccomp unavailable: seccomp(SECCOMP_SET_MODE_FILTER, BOGUS_FLAG) returned " + ret);
} else {
int errno = Native.getLastError();
switch (errno) {
case ENOSYS: break; // ok
throw new UnsupportedOperationException("seccomp unavailable: prctl(BOGUS_OPTION) returned " + ret);
} else {
int errno = Native.getLastError();
switch (errno) {
case ENOSYS: break; // ok
case 1: break; // already set by caller
default:
int errno = Native.getLastError();
if (errno == EINVAL) {
case 2: break; // already in filter mode by caller
default:
int errno = Native.getLastError();
if (errno == EINVAL) {
throw new UnsupportedOperationException("seccomp unavailable: CONFIG_SECCOMP not compiled into kernel," +
代码示例来源:origin: org.elasticsearch/elasticsearch
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");
}
代码示例来源:origin: org.elasticsearch/elasticsearch
logger.warn("Unable to lock JVM memory. Failed to set working set size. Error code {}", Native.getLastError());
} else {
JNAKernel32Library.MemoryBasicInformation memInfo = new JNAKernel32Library.MemoryBasicInformation();
long address = 0;
while (kernel.VirtualQueryEx(process, new Pointer(address), memInfo, memInfo.size()) != 0) {
boolean lockable = memInfo.State.longValue() == JNAKernel32Library.MEM_COMMIT
&& (memInfo.Protect.longValue() & JNAKernel32Library.PAGE_NOACCESS) != JNAKernel32Library.PAGE_NOACCESS
&& (memInfo.Protect.longValue() & JNAKernel32Library.PAGE_GUARD) != JNAKernel32Library.PAGE_GUARD;
if (lockable) {
kernel.VirtualLock(memInfo.BaseAddress, new SizeT(memInfo.RegionSize.longValue()));
代码示例来源:origin: org.elasticsearch/elasticsearch
static void bsdImpl() {
boolean supported = Constants.FREE_BSD || OPENBSD || Constants.MAC_OS_X;
if (supported == false) {
throw new IllegalStateException("bug: should not be trying to initialize RLIMIT_NPROC for an unsupported OS");
}
JNACLibrary.Rlimit limit = new JNACLibrary.Rlimit();
limit.rlim_cur.setValue(0);
limit.rlim_max.setValue(0);
if (JNACLibrary.setrlimit(RLIMIT_NPROC, limit) != 0) {
throw new UnsupportedOperationException("RLIMIT_NPROC unavailable: " + JNACLibrary.strerror(Native.getLastError()));
}
logger.debug("BSD RLIMIT_NPROC initialization successful");
}
代码示例来源:origin: org.elasticsearch/elasticsearch
/**
* Retrieves the short path form of the specified path.
*
* @param path the path
* @return the short path name (or the original path if getting the short path name fails for any reason)
*/
static String getShortPathName(String path) {
assert Constants.WINDOWS;
try {
final WString longPath = new WString("\\\\?\\" + path);
// first we get the length of the buffer needed
final int length = JNAKernel32Library.getInstance().GetShortPathNameW(longPath, null, 0);
if (length == 0) {
logger.warn("failed to get short path name: {}", Native.getLastError());
return path;
}
final char[] shortPath = new char[length];
// knowing the length of the buffer, now we get the short name
if (JNAKernel32Library.getInstance().GetShortPathNameW(longPath, shortPath, length) > 0) {
return Native.toString(shortPath);
} else {
logger.warn("failed to get short path name: {}", Native.getLastError());
return path;
}
} catch (final UnsatisfiedLinkError e) {
return path;
}
}
代码示例来源:origin: kaitoy/pcap4j
private MacAddress getMacAddress(String nifName) {
Pointer lpAdapter = NativePacketDllMappings.PacketOpenAdapter(nifName);
long hFile = -1;
if (lpAdapter != null) {
if (Native.POINTER_SIZE == 4) {
hFile = lpAdapter.getInt(0);
} else {
hFile = lpAdapter.getLong(0);
}
}
if (hFile == -1L) {
int err = Native.getLastError();
logger.error("Unable to open the NIF {}, Error Code: {}", nifName, err);
return null;
}
Memory mem = new Memory(NativePacketDllMappings.PACKET_OID_DATA_SIZE);
mem.clear();
PACKET_OID_DATA oidData = new PACKET_OID_DATA(mem);
oidData.Length = new NativeLong(6L);
oidData.Oid = new NativeLong(0x01010102L);
int status = NativePacketDllMappings.PacketRequest(lpAdapter, 0, oidData);
NativePacketDllMappings.PacketCloseAdapter(lpAdapter);
if (status == 0) {
logger.error("Failed to retrieve the link layer address of the NIF: {}", nifName);
return null;
} else {
return MacAddress.getByAddress(oidData.Data);
}
}
代码示例来源:origin: net.java.dev.jna/jna-platform
/**
* Retrieves the name of the user associated with the current thread.
*
* @return A user name.
*/
public static String getUserName() {
char[] buffer = new char[128];
IntByReference len = new IntByReference(buffer.length);
boolean result = Advapi32.INSTANCE.GetUserNameW(buffer, len);
if (!result) {
switch (Kernel32.INSTANCE.GetLastError()) {
case W32Errors.ERROR_INSUFFICIENT_BUFFER:
buffer = new char[len.getValue()];
break;
default:
throw new Win32Exception(Native.getLastError());
}
result = Advapi32.INSTANCE.GetUserNameW(buffer, len);
}
if (!result) {
throw new Win32Exception(Native.getLastError());
}
return Native.toString(buffer);
}
代码示例来源:origin: org.kohsuke/akuma
private static String resolveSymlink(File link) throws IOException {
String filename = link.getAbsolutePath();
for (int sz=512; sz < 65536; sz*=2) {
Memory m = new Memory(sz);
int r = LIBC.readlink(filename,m,new NativeLong(sz));
if (r<0) {
int err = Native.getLastError();
if (err==22/*EINVAL --- but is this really portable?*/)
return null; // this means it's not a symlink
throw new IOException("Failed to readlink "+link+" error="+ err+" "+ LIBC.strerror(err));
}
if (r==sz)
continue; // buffer too small
byte[] buf = new byte[r];
m.read(0,buf,0,r);
return new String(buf);
}
throw new IOException("Failed to readlink "+link);
}
代码示例来源:origin: org.seleniumhq.webdriver/webdriver-ie
private String extractString(ExportedWebDriverFunctions lib, Pointer string) {
IntByReference length = new IntByReference();
if (lib.wdStringLength(string, length) != SUCCESS) {
lib.wdFreeString(string);
throw new RuntimeException("Cannot determine length of string");
}
char[] rawString = new char[length.getValue()];
if (lib.wdCopyString(string, length.getValue(), rawString) != SUCCESS) {
lib.wdFreeString(string);
throw new RuntimeException("Cannot copy string from native data to Java string");
}
String value = Native.toString(rawString);
lib.wdFreeString(string);
return value;
}
代码示例来源:origin: jenkinsci/jenkins
envVars = new EnvVars();
IntByReference intByRef = new IntByReference();
IntByReference argmaxRef = new IntByReference(0);
IntByReference size = new IntByReference(sizeOfInt);
if(LIBC.sysctl(new int[]{CTL_KERN,KERN_ARGMAX},2, argmaxRef.getPointer(), size, NULL, intByRef)!=0)
throw new IOException("Failed to get kern.argmax: "+LIBC.strerror(Native.getLastError()));
int argmax = argmaxRef.getValue();
size.setValue(argmax);
if(LIBC.sysctl(new int[]{CTL_KERN,KERN_PROCARGS2,pid},3, m, size, NULL, intByRef)!=0)
throw new IOException("Failed to obtain ken.procargs2: "+LIBC.strerror(Native.getLastError()));
代码示例来源:origin: net.java.dev.jna/jna-platform
retval = XAttr.INSTANCE.fgetxattr(fd, name, (Memory) null, size_t.ZERO);
if (retval.longValue() < 0) {
eno = Native.getLastError();
throw new IOException("errno: " + eno);
valueMem = new Memory(retval.longValue());
retval = XAttr.INSTANCE.fgetxattr(fd, name, valueMem, new size_t(valueMem.size()));
if (retval.longValue() < 0) {
eno = Native.getLastError();
if (eno != XAttr.ERANGE) {
throw new IOException("errno: " + eno);
内容来源于网络,如有侵权,请联系作者删除!