本文整理了Java中com.sun.jna.Memory
类的一些代码示例,展示了Memory
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Memory
类的具体详情如下:
包路径:com.sun.jna.Memory
类名称:Memory
[英]A Pointer
to memory obtained from the native heap via a call to malloc
.
In some cases it might be necessary to use memory obtained from malloc
. For example, Memory
helps accomplish the following idiom:
void *buf = malloc(BUF_LEN * sizeof(char));
call_some_function(buf);
free(buf);
The #finalize method will free allocated memory when this object is no longer referenced.
[中]通过调用malloc
从本机堆获得的Pointer
内存。
在某些情况下,可能需要使用从malloc
获得的内存。例如,Memory
有助于实现以下习惯用法:
void *buf = malloc(BUF_LEN * sizeof(char));
call_some_function(buf);
free(buf);
当不再引用此对象时,#finalize方法将释放分配的内存。
代码示例来源: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: net.java.dev.jna/jna
/** Provide a view of this memory using the given offset as the base address. The
* returned {@link Pointer} will have a size equal to that of the original
* minus the offset.
* @throws IndexOutOfBoundsException if the requested memory is outside
* the allocated bounds.
*/
@Override
public Pointer share(long offset) {
return share(offset, size() - offset);
}
代码示例来源:origin: jenkinsci/jenkins
Memory m = new Memory(psize);
int fd = LIBC.open(getFile("as").getAbsolutePath(), 0);
LIBC.pread(fd, m, new NativeLong(psize), new NativeLong(pr_argp));
long argp = b64 ? m.getLong(0) : to64(m.getInt(0));
LIBC.pread(fd, m, new NativeLong(psize), new NativeLong(argp+(n*psize)));
long addr = b64 ? m.getLong(0) : to64(m.getInt(0));
代码示例来源:origin: jenkinsci/jenkins
public static File getTempDir() {
Memory buf = new Memory(1024);
if (Kernel32.INSTANCE.GetTempPathW(512,buf)!=0) {// the first arg is number of wchar
return new File(buf.getString(0, true));
} else {
return null;
}
}
代码示例来源:origin: jenkinsci/jenkins
private String readLine(int fd, long addr, String prefix) throws IOException {
if(LOGGER.isLoggable(FINEST))
LOGGER.finest("Reading "+prefix+" at "+addr);
Memory m = new Memory(1);
byte ch = 1;
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int i = 0;
while(true) {
if (i++ > LINE_LENGTH_LIMIT) {
LOGGER.finest("could not find end of line, giving up");
throw new IOException("could not find end of line, giving up");
}
long r = LIBC.pread(fd, m, new NativeLong(1), new NativeLong(addr));
ch = m.getByte(0);
if (ch == 0)
break;
buf.write(ch);
addr++;
}
String line = buf.toString();
if(LOGGER.isLoggable(FINEST))
LOGGER.finest(prefix+" was "+line);
return line;
}
}
代码示例来源:origin: broadgsa/gatk
private static List<String> getJobIds(PointerByReference jobIds) throws DrmaaException {
List<String> jobIdsList = new ArrayList<String>();
IntByReference size = new IntByReference();
int errnum;
errnum = LibDrmaa.drmaa_get_num_job_ids(jobIds.getValue(), size);
checkError(errnum, "unable to get jobIds");
int num = size.getValue();
Memory value = new Memory(LibDrmaa.DRMAA_JOBNAME_BUFFER);
for (int i = 1; i <= num; i++) {
errnum = LibDrmaa.drmaa_get_next_job_id(jobIds.getValue(), value, LibDrmaa.DRMAA_JOBNAME_BUFFER_LEN);
checkError(errnum, "unable to get jobId " + i);
if (errnum == LibDrmaa.DRMAA_ERRNO.DRMAA_ERRNO_NO_MORE_ELEMENTS)
break;
jobIdsList.add(value.getString(0));
}
return jobIdsList;
}
代码示例来源:origin: mmarquee/ui-automation
/**
* Gets the version info (if present) from the file in the path.
* @param path Pathname to file
* @return The version info array (loads of integers)
*/
public static int[] getVersionInfo(final String path) {
IntByReference dwDummy = new IntByReference();
dwDummy.setValue(0);
int versionlength = com.sun.jna.platform.win32.Version.INSTANCE.GetFileVersionInfoSize(path, dwDummy);
byte[] bufferarray = new byte[versionlength];
Pointer lpData = new Memory(bufferarray.length);
PointerByReference lplpBuffer = new PointerByReference();
IntByReference puLen = new IntByReference();
com.sun.jna.platform.win32.Version.INSTANCE.GetFileVersionInfo(path, 0, versionlength, lpData);
com.sun.jna.platform.win32.Version.INSTANCE.VerQueryValue(lpData, "\\", lplpBuffer, puLen);
VerRsrc.VS_FIXEDFILEINFO lplpBufStructure = new VerRsrc.VS_FIXEDFILEINFO(lplpBuffer.getValue());
lplpBufStructure.read();
int v1 = (lplpBufStructure.dwFileVersionMS).intValue() >> 16;
int v2 = (lplpBufStructure.dwFileVersionMS).intValue() & 0xffff;
int v3 = (lplpBufStructure.dwFileVersionLS).intValue() >> 16;
int v4 = (lplpBufStructure.dwFileVersionLS).intValue() & 0xffff;
System.out.println("Version: " + v1 + "." + v2 + "." + v3 + "." + v4);
return new int[]{v1, v2, v3, v4};
}
}
代码示例来源:origin: ch.epfl.scala/command
@Override
public int read(byte[] b, int off, int len) throws IOException {
Memory readBuffer = new Memory(len);
WinBase.OVERLAPPED olap = new WinBase.OVERLAPPED();
olap.hEvent = readerWaitable;
olap.write();
boolean immediate = API.ReadFile(handle, readBuffer, len, null, olap.getPointer());
if (!immediate) {
int lastError = API.GetLastError();
if (lastError != WinError.ERROR_IO_PENDING) {
throw new IOException("ReadFile() failed: " + lastError);
}
}
IntByReference read = new IntByReference();
if (!API.GetOverlappedResult(handle, olap.getPointer(), read, true)) {
int lastError = API.GetLastError();
throw new IOException("GetOverlappedResult() failed for read operation: " + lastError);
}
int actualLen = read.getValue();
byte[] byteArray = readBuffer.getByteArray(0, actualLen);
System.arraycopy(byteArray, 0, b, off, actualLen);
return actualLen;
}
}
代码示例来源:origin: stackoverflow.com
int strSize = 255;
int result = 0;
IntByReference byteIO = new IntByReference();
Pointer lngVarPtr1 = null;Pointer lngMemVar1 = null;
Pointer lngVarPtr2 = null;Pointer lngMemVar2 = null;
int lngMemLen1; int lngMemLen2;
lngProcID = new PointerByReference();
int ThreadId = user32.GetWindowThreadProcessId(hWnd, lngProcID);
lngProcHandle = Kernel32.OpenProcess(Kernel32.PROCESS_VM_OPERATION | Kernel32.PROCESS_VM_WRITE | Kernel32.PROCESS_VM_READ, false, lngProcID.getValue());
lngVarPtr1 = new Memory(strSize + 1);
result = Kernel32.ReadProcessMemory(lngProcHandle, lngMemVar1, lngVarPtr1, lngMemLen1, byteIO);
result = Kernel32.CloseHandle(lngProcHandle);
return lngVarPtr1.getWideString(0);
代码示例来源: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: com.googlecode.gstreamer-java/gstreamer-java
public NativeArgs(String progname, String[] args) {
//
// Allocate some native memory to pass the args down to the native layer
//
argsCopy = new Memory[args.length + 2];
argvMemory = new Memory(argsCopy.length * Pointer.SIZE);
//
// Insert the program name as argv[0]
//
Memory arg = new Memory(progname.getBytes().length + 4);
arg.setString(0, progname, false);
argsCopy[0] = arg;
for (int i = 0; i < args.length; i++) {
arg = new Memory(args[i].getBytes().length + 1);
arg.setString(0, args[i], false);
argsCopy[i + 1] = arg;
}
argvMemory.write(0, argsCopy, 0, argsCopy.length);
argvRef = new PointerByReference(argvMemory);
argcRef = new IntByReference(args.length + 1);
}
String[] toStringArray() {
代码示例来源:origin: net.openhft/affinity
byte[] buff = affinity.toByteArray();
final int cpuSetSizeInBytes = buff.length;
final Memory cpusetArray = new Memory(cpuSetSizeInBytes);
try {
cpusetArray.write(0, buff, 0, buff.length);
final int ret = lib.sched_setaffinity(0, cpuSetSizeInBytes, new PointerByReference(cpusetArray));
if (ret < 0) {
throw new IllegalStateException("sched_setaffinity((" + cpuSetSizeInBytes + ") , &(" + affinity + ") ) return " + ret);
if (e.getErrorCode() != 22 || !Arrays.equals(buff, cpusetArray.getByteArray(0, cpuSetSizeInBytes))) {
throw new IllegalStateException("sched_setaffinity((" + cpuSetSizeInBytes + ") , &(" + affinity + ") ) errorNo=" + e.getErrorCode(), e);
throw new IllegalArgumentException("Cannot set zero affinity");
final IntByReference cpuset32 = new IntByReference(0);
cpuset32.setValue(value);
try {
final int ret = lib.sched_setaffinity(0, Integer.SIZE / 8, cpuset32);
if (ret < 0)
throw new IllegalStateException("sched_setaffinity((" + Integer.SIZE / 8 + ") , &(" + Integer.toHexString(cpuset32.getValue()) + ") ) return " + ret);
} catch (LastErrorException e) {
throw new IllegalStateException("sched_setaffinity((" + Integer.SIZE / 8 + ") , &(" + Integer.toHexString(cpuset32.getValue()) + ") ) errorNo=" + e.getErrorCode(), e);
代码示例来源:origin: org.jvnet.libzfs/libzfs
public String getZfsProperty(zfs_prop_t prop) {
Memory propbuf = new Memory(libzfs.ZFS_MAXPROPLEN);
char[] buf = null;
IntByReference ibr = null;
int ret = LIBZFS.zfs_prop_get(handle, new NativeLong(prop.ordinal()),
propbuf, libzfs.ZFS_MAXPROPLEN, ibr, buf,
new NativeLong(0), true);
return ((ret != 0) ? null : propbuf.getString(0));
}
代码示例来源:origin: net.java.dev.jna/jna-platform
IntByReference dwDummy = new IntByReference();
throw new Win32Exception(Native.getLastError());
Pointer lpData = new Memory(versionLength);
PointerByReference lplpBuffer = new PointerByReference();
throw new Win32Exception(Native.getLastError());
IntByReference puLen = new IntByReference();
VS_FIXEDFILEINFO fileInfo = new VS_FIXEDFILEINFO(lplpBuffer.getValue());
fileInfo.read();
return fileInfo;
代码示例来源:origin: org.tmatesoft.svnkit/svnkit
public DATA_BLOB(byte[] bytes) {
if (bytes != null) {
int allocationSize = Math.max(1, bytes.length);
cbData = new Memory(allocationSize);
cbData.write(0, bytes, 0, bytes.length);
cbSize = new NativeLong(bytes.length);
} else {
cbSize = new NativeLong(0);
cbData = Pointer.NULL;
}
}
代码示例来源:origin: jMonkeyEngine/jmonkeyengine
Pointer pchValue = new Memory(unBufferSize);
IntByReference pError = new IntByReference();
if (pError.getValue() == ETrackedPropertyError.ETrackedPropertyError_TrackedProp_Success){
str = pchValue.getString(0);
} else if (pError.getValue() == ETrackedPropertyError.ETrackedPropertyError_TrackedProp_BufferTooSmall){
throw new IllegalArgumentException("Cannot access property \""+getETrackedDevicePropertyString(property)+"\" ("+property+") for device "+deviceIndex+": "+getETrackedPropertyErrorString(pError.getValue())+" ("+pError.getValue()+")");
} else if (pError.getValue() == ETrackedPropertyError.ETrackedPropertyError_TrackedProp_CouldNotContactServer){
代码示例来源: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.zeromq/zeromq-scala-binding
private zmq_msg_t newZmqMessage(byte[] msg) {
zmq_msg_t message = new zmq_msg_t();
if (msg.length == 0) {
if (zmq.zmq_msg_init_size(message, new NativeLong(msg.length)) != 0) {
raiseZMQException();
}
} else {
Memory mem = new Memory(msg.length);
mem.write(0, msg, 0, msg.length);
if (zmq.zmq_msg_init_data(message, mem, new NativeLong(msg.length), messageDataBuffer, mem) == 0) {
messageDataBuffer.add(mem);
} else {
raiseZMQException();
}
}
return message;
}
代码示例来源:origin: net.java.dev.jna/jna-platform
retval = XAttr.INSTANCE.getxattr(path, 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.getxattr(path, name, valueMem, new size_t(valueMem.size()));
if (retval.longValue() < 0) {
eno = Native.getLastError();
if (eno != XAttr.ERANGE) {
throw new IOException("errno: " + eno);
代码示例来源:origin: net.java.dev.jna/jna-platform
/**
* Gets the specified channel configuration property.
*
* @param channelHandle [in] A handle to the channel's configuration properties that
* the {@link Wevtapi#EvtOpenChannelConfig} function returns.
* @param propertyId [in] The identifier of the channel property to retrieve. For a list of property
* identifiers, see the {@link Winevt.EVT_CHANNEL_CONFIG_PROPERTY_ID} enumeration.
* @return EVT_VARIANT(already reading from native memory)
*/
public static EVT_VARIANT EvtGetChannelConfigProperty(EVT_HANDLE channelHandle, int propertyId) {
IntByReference propertyValueBufferUsed = new IntByReference();
boolean result = Wevtapi.INSTANCE.EvtGetChannelConfigProperty(channelHandle, propertyId, 0, 0, null, propertyValueBufferUsed);
int errorCode = Kernel32.INSTANCE.GetLastError();
if ((!result) && errorCode != Kernel32.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(errorCode);
}
Memory propertyValueBuffer = new Memory(propertyValueBufferUsed.getValue());
result = Wevtapi.INSTANCE.EvtGetChannelConfigProperty(channelHandle, propertyId, 0, (int) propertyValueBuffer.size(),
propertyValueBuffer, propertyValueBufferUsed);
if (!result) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
EVT_VARIANT resultEvt = new EVT_VARIANT(propertyValueBuffer);
resultEvt.read();
return resultEvt;
}
内容来源于网络,如有侵权,请联系作者删除!