ref 订阅
.net的关键字 [1]  ,ref关键字--让参数按照引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中;也等同将值类型的数据使用引用方式传参。若要使用ref参数,则方法定义和调用方法都必须显示使用ref关键字。ref是 Reference的缩写。 展开全文
.net的关键字 [1]  ,ref关键字--让参数按照引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中;也等同将值类型的数据使用引用方式传参。若要使用ref参数,则方法定义和调用方法都必须显示使用ref关键字。ref是 Reference的缩写。
信息
引用方法
显式使用
外文名
ref
用    途
C#中关键字通过引用传递参数
中文名
ref
proteus功能特点
例如:传递到ref参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。尽管ref和out在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用ref参数,而另一个方法采用out 参数,则无法重载这两个方法。注意:属性不是变量,因此不能作为ref参数传递。ref和out两个参数的不同在于:1、ref传进去的参数必须在调用前初始化,out不必,即:2、ref传进去的参数在函数内部可以直接使用,而out不可:3、ref传进去的参数在函数内部可以不被修改,但out必须在离开函数体前进行赋值。
收起全文
精华内容
下载资源
问答
  • ref

    千次阅读 2017-12-21 23:53:21
    Examples referencing ...var ref = require('ref') // so we can all agree that a buffer with the int value written // to it could be represented as an "int *" var buf = new Buffer

    Examples

    referencing and derefencing

    var ref = require('ref')
    
    // so we can all agree that a buffer with the int value written
    // to it could be represented as an "int *"
    var buf = new Buffer(4)
    buf.writeInt32LE(12345, 0)
    
    // first, what is the memory address of the buffer?
    console.log(buf.hexAddress())  // ← '7FA89D006FD8'
    
    // using `ref`, you can set the "type", and gain magic abilities!
    buf.type = ref.types.int
    
    // now we can dereference to get the "meaningful" value
    console.log(buf.deref())  // ← 12345
    
    
    // you can also get references to the original buffer if you need it.
    // this buffer could be thought of as an "int **"
    var one = buf.ref()
    
    // and you can dereference all the way back down to an int
    console.log(one.deref().deref())  // ← 12345

    See the full API Docs for more examples.

    The "type" interface

    You can easily define your own "type" objects at attach to Buffer instances. It just needs to be a regular JavaScript Object that contains the following properties:

    Name Data Type Description
    size Number The size in bytes required to hold this type.
    indirection Number The current level of indirection of the buffer. Usually this would be 1, and gets incremented on Buffers from ref() calls. A value of less than or equal to 0 is invalid.
    get Function (buffer, offset) The function to invoke when dereferencing this type when the indirection level is 1.
    set Function (buffer, offset, value) The function to invoke when setting a value to a buffer instance.
    name String (optional) The name to use during debugging for this type.
    alignment Number (optional) The alignment of this type when placed in a struct. Defaults to the type's size.

    Be sure to check out the Wiki page of "Known Types", for the list of built-in ref types, as well as known external type implementations.

    For example, you could define a "bigint" type that dereferences into a bigint instance:

    var ref = require('ref')
    var bigint = require('bigint')
    
    // define the "type" instance according to the spec
    var BigintType = {
        size: ref.sizeof.int64
      , indirection: 1
      , get: function (buffer, offset) {
          // return a bigint instance from the buffer
          return bigint.fromBuffer(buffer)
        }
      , set: function (buffer, offset, value) {
          // 'value' would be a bigint instance
          var val = value.toString()
          return ref.writeInt64(buffer, offset || 0, val)
        }
    }
    
    // now we can create instances of the type from existing buffers.
    // "buf" is some Buffer instance returned from some external data
    // source, which should contain "bigint" binary data.
    buf.type = BigintType
    
    // and now you can create "bigint" instances using this generic "types" API
    var val = buf.deref()
                .add('1234')
                .sqrt()
                .shiftLeft(5)
    
    
    
    
    
    
    
    

    Turn Buffer instances into "pointers"

    What is ref?

    ref is a native addon for Node.js that aids in doing C programming in JavaScript, by extending the built-in Buffer class with some fancy additions like:

    • Getting the memory address of a Buffer
    • Checking the endianness of the processor
    • Checking if a Buffer represents the NULL pointer
    • Reading and writing "pointers" with Buffers
    • Reading and writing C Strings (NULL-terminated)
    • Reading and writing JavaScript Object references
    • Reading and writing int64_t and uint64_t values
    • A "type" convention to define the contents of a Buffer

    There is indeed a lot of meat to ref, but it all fits together in one way or another in the end. For simplicity, ref's API can be broken down into 3 sections:

    ref exports

    All the static versions of ref's functions and default "types" available on the exports returned from require('ref').

    "type" system

    The "type" system allows you to define a "type" on any Buffer instance, and then use generic ref() and deref() functions to reference and dereference values.

    Buffer extensions

    Buffer.prototype gets extended with some convenience functions. These all just mirror their static counterpart, using the Buffer's this variable as the buffer variable.


    ref exports

    This section documents all the functions exported from require('ref').

    ref.NULL ⇒ Buffer

    Buffer that references the C NULL pointer. That is, its memory address points to 0. Its length is 0 because accessing any data from this buffer would cause a segmentation fault.

    console.log(ref.NULL);
    <SlowBuffer@0x0 >
    

    ref.NULL_POINTER ⇒ Buffer

    NULL_POINTER is a pointer-sized Buffer instance pointing to NULL. Conceptually, it's equivalent to the following C code:

    char *null_pointer;
    null_pointer = NULL;
    

    ref.address(Buffer buffer→ Number

    • buffer - The buffer to get the memory address of.
    • Return: The memory address the buffer instance.

    Accepts a Buffer instance and returns the memory address of the buffer instance.

    console.log(ref.address(new Buffer(1)));
    4320233616
    
    console.log(ref.address(ref.NULL)));
    0
    

    ref.alloc(Object|String type? value→ Buffer

    • type - The "type" object to allocate. Strings get coerced first.
    • value - (optional) The initial value set on the returned Buffer, using type's set() function.
    • Return: A new Buffer instance with it's type set to "type", and (optionally) "value" written to it.

    Returns a new Buffer instance big enough to hold type, with the given value written to it.

    var intBuf = ref.alloc(ref.types.int)
    var int_with_4 = ref.alloc(ref.types.int, 4)
    

    ref.allocCString(String stringString encoding→ Buffer

    • string - The JavaScript string to be converted to a C string.
    • encoding - (optional) The encoding to use for the C string. Defaults to 'utf8'.
    • Return: The new Buffer instance with the specified String wrtten to it, and a trailing NUL byte.

    Returns a new Buffer instance with the given String written to it with the given encoding (defaults to 'utf8'). The buffer is 1 byte longer than the string itself, and is NUL terminated.

    var buf = ref.allocCString('hello world');
    
    console.log(buf.toString());
    'hello world\u0000'
    

    ref.coerceType(Object|String type→ Object

    • type - The "type" Object or String to coerce.
    • Return: A "type" object

    Coerces a "type" object from a String or an actual "type" object. String values are looked up from the ref.types Object. So:

    • "int" gets coerced into ref.types.int.
    • "int *" gets translated into ref.refType(ref.types.int)
    • ref.types.int gets translated into ref.types.int (returns itself)

    Throws an Error if no valid "type" object could be determined. Most ref functions use this function under the hood, so anywhere a "type" object is expected, a String may be passed as well, including simply setting the buffer.type property.

    var type = ref.coerceType('int **');
    
    console.log(type.indirection);
    3
    

    ref.deref(Buffer buffer→ ?

    • buffer - A Buffer instance to dereference.
    • Return: The returned value after dereferencing buffer.

    Accepts a Buffer instance and attempts to "dereference" it. That is, first it checks the indirection count of buffer's "type", and if it's greater than 1 then it merely returns another Buffer, but with one level less indirection.

    When buffer's indirection is at 1, then it checks for buffer.type which should be an Object with its own get() function.

    var buf = ref.alloc('int', 6);
    
    var val = ref.deref(buf);
    console.log(val);
    6
    

    ref.derefType(Object|String type→ Object

    • type - The "type" object to create a dereference type from. Strings get coerced first.
    • Return: The new "type" object with its indirection decremented by 1.

    Returns a new clone of the given "type" object, with its indirection level decremented by 1.

    ref.endianness ⇒ String

    A string that represents the native endianness of the machine's processor. The possible values are either "LE" or "BE".

    console.log(ref.endianness);
    'LE'
    

    ref.get(Buffer bufferNumber offsetObject|String type→ ?

    • buffer - The Buffer instance to read from.
    • offset - (optional) The offset on the Buffer to start reading from. Defaults to 0.
    • type - (optional) The "type" object to use when reading. Defaults to calling getType() on the buffer.
    • Return: Whatever value the "type" used when reading returns.

    Calls the get() function of the Buffer's current "type" (or the passed in type if present) at the given offset.

    This function handles checking the "indirection" level and returning a proper "dereferenced" Bufffer instance when necessary.

    ref.getType(Buffer buffer→ Object

    • buffer - The Buffer instance to get the "type" object from.
    • Return: The "type" object from the given Buffer.

    Returns the "type" property of the given Buffer. Creates a default type for the buffer when none exists.

    ref.isNull(Buffer buffer→ Boolean

    • buffer - The buffer to check for NULL.
    • Return: true or false.

    Accepts a Buffer instance and returns true if the buffer represents the NULL pointer, false otherwise.

    console.log(ref.isNull(new Buffer(1)));
    false
    
    console.log(ref.isNull(ref.NULL));
    true
    

    ref.readCString(Buffer bufferNumber offset→ String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The String that was read from buffer.

    Returns a JavaScript String read from buffer at the given offset. The C String is read until the first NULL byte, which indicates the end of the String.

    This function can read beyond the length of a Buffer.

    var buf = new Buffer('hello\0world\0');
    
    var str = ref.readCString(buf, 0);
    console.log(str);
    'hello'
    

    ref.readInt64BE(Buffer bufferNumber offset→ Number|String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The Number or String that was read from buffer.

    Returns a big-endian signed 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('int64');
    ref.writeInt64BE(buf, 0, '9223372036854775807');
    
    var val = ref.readInt64BE(buf, 0)
    console.log(val)
    '9223372036854775807'
    

    ref.readInt64LE(Buffer bufferNumber offset→ Number|String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The Number or String that was read from buffer.

    Returns a little-endian signed 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('int64');
    ref.writeInt64LE(buf, 0, '9223372036854775807');
    
    var val = ref.readInt64LE(buf, 0)
    console.log(val)
    '9223372036854775807'
    

    ref.readObject(Buffer bufferNumber offset→ Object

    • buffer - The buffer to read an Object from.
    • offset - The offset to begin reading from.
    • Return: The Object that was read from buffer.

    Reads a JavaScript Object that has previously been written to the given buffer at the given offset.

    var obj = { foo: 'bar' };
    var buf = ref.alloc('Object', obj);
    
    var obj2 = ref.readObject(buf, 0);
    console.log(obj === obj2);
    true
    

    ref.readPointer(Buffer bufferNumber offsetNumber length→ Buffer

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • length - (optional) The length of the returned Buffer. Defaults to 0.
    • Return: The Buffer instance that was read from buffer.

    Reads a Buffer instance from the given buffer at the given offset. The size parameter specifies the length of the returned Buffer instance, which defaults to 0.

    var buf = new Buffer('hello world');
    var pointer = ref.alloc('pointer');
    
    var buf2 = ref.readPointer(pointer, 0, buf.length);
    console.log(buf.toString());
    'hello world'
    

    ref.readUInt64BE(Buffer bufferNumber offset→ Number|String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The Number or String that was read from buffer.

    Returns a big-endian unsigned 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('uint64');
    ref.writeUInt64BE(buf, 0, '18446744073709551615');
    
    var val = ref.readUInt64BE(buf, 0)
    console.log(val)
    '18446744073709551615'
    

    ref.readUInt64LE(Buffer bufferNumber offset→ Number|String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The Number or String that was read from buffer.

    Returns a little-endian unsigned 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('uint64');
    ref.writeUInt64LE(buf, 0, '18446744073709551615');
    
    var val = ref.readUInt64LE(buf, 0)
    console.log(val)
    '18446744073709551615'
    

    ref.ref(Buffer buffer→ Buffer

    • buffer - A Buffer instance to create a reference to.
    • Return: A new Buffer instance pointing to buffer.

    ref() accepts a Buffer instance and returns a new Buffer instance that is "pointer" sized and has its data pointing to the given Buffer instance. Essentially the created Buffer is a "reference" to the original pointer, equivalent to the following C code:

    char *buf = buffer;
    char **ref = &buf;
    

    ref.refType(Object|String type→ Object

    • type - The "type" object to create a reference type from. Strings get coerced first.
    • Return: The new "type" object with its indirection incremented by 1.

    Returns a new clone of the given "type" object, with its indirection level incremented by 1.

    Say you wanted to create a type representing a void *:

    var voidPtrType = ref.refType(ref.types.void);
    

    ref.reinterpret(Buffer bufferNumber sizeNumber offset→ Buffer

    • buffer - A Buffer instance to base the returned Buffer off of.
    • size - The length property of the returned Buffer.
    • offset - The offset of the Buffer to begin from.
    • Return: A new Buffer instance with the same memory address as buffer, and the requested size.

    Returns a new Buffer instance with the specified size, with the same memory address as buffer.

    This function "attaches" buffer to the returned Buffer to prevent it from being garbage collected.

    ref.reinterpretUntilZeros(Buffer bufferNumber sizeNumber offset→ Buffer

    • buffer - A Buffer instance to base the returned Buffer off of.
    • size - The number of sequential, aligned NULL bytes are required to terminate the buffer.
    • offset - The offset of the Buffer to begin from.
    • Return: A new Buffer instance with the same memory address as buffer, and a variable length that is terminated by size NUL bytes.

    Accepts a Buffer instance and a number of NULL bytes to read from the pointer. This function will scan past the boundary of the Buffer's length until it finds size number of aligned NULL bytes.

    This is useful for finding the end of NUL-termintated array or C string. For example, the readCString() function could be implemented like:

    function readCString (buf) {
      return ref.reinterpretUntilZeros(buf, 1).toString('utf8')
    }
    

    This function "attaches" buffer to the returned Buffer to prevent it from being garbage collected.

    ref.set(Buffer bufferNumber offset? valueObject|String type)

    • buffer - The Buffer instance to write to.
    • offset - The offset on the Buffer to start writing to.
    • value - The value to write to the Buffer instance.
    • type - (optional) The "type" object to use when reading. Defaults to calling getType() on the buffer.

    Calls the set() function of the Buffer's current "type" (or the passed in type if present) at the given offset.

    This function handles checking the "indirection" level writing a pointer rather than calling the set() function if the indirection is greater than 1.

    ref.writeCString(Buffer bufferNumber offsetString stringString encoding)

    • buffer - The Buffer instance to write to.
    • offset - The offset of the buffer to begin writing at.
    • string - The JavaScript String to write that will be written to the buffer.
    • encoding - (optional) The encoding to read the C string as. Defaults to 'utf8'.

    Writes the given string as a C String (NULL terminated) to the given buffer at the given offset. "encoding" is optional and defaults to 'utf8'.

    Unlike readCString(), this function requires the buffer to actually have the proper length.

    ref.writeInt64BE(Buffer bufferNumber offsetNumber|String input)

    • buffer - The buffer to write to.
    • offset - The offset to begin writing from.
    • input - This String or Number which gets written.

    Writes the input Number or String as a big-endian signed 64-bit int into buffer at the given offset.

    var buf = ref.alloc('int64');
    ref.writeInt64BE(buf, 0, '9223372036854775807');
    

    ref.writeInt64LE(Buffer bufferNumber offsetNumber|String input)

    • buffer - The buffer to write to.
    • offset - The offset to begin writing from.
    • input - This String or Number which gets written.

    Writes the input Number or String as a little-endian signed 64-bit int into buffer at the given offset.

    var buf = ref.alloc('int64');
    ref.writeInt64LE(buf, 0, '9223372036854775807');
    

    ref.writeObject(Buffer bufferNumber offsetObject object)

    • buffer - A Buffer instance to write object to.
    • offset - The offset on the Buffer to start writing at.
    • object - The Object to be written into buffer.

    Writes a pointer to object into buffer at the specified _offset.

    This function "attaches" object to buffer to prevent it from being garbage collected.

    var buf = ref.alloc('Object');
    ref.writeObject(buf, 0, { foo: 'bar' });
    

    ref.writePointer(Buffer bufferNumber offsetBuffer pointer)

    • buffer - A Buffer instance to write _pointer to.
    • offset - The offset on the Buffer to start writing at.
    • pointer - The Buffer instance whose memory address will be written to buffer.

    Writes the memory address of pointer to buffer at the specified offset.

    This function "attaches" object to buffer to prevent it from being garbage collected.

    var someBuffer = new Buffer('whatever');
    var buf = ref.alloc('pointer');
    ref.writePointer(buf, 0, someBuffer);
    

    ref.writeUInt64BE(Buffer bufferNumber offsetNumber|String input)

    • buffer - The buffer to write to.
    • offset - The offset to begin writing from.
    • input - This String or Number which gets written.

    Writes the input Number or String as a big-endian unsigned 64-bit int into buffer at the given offset.

    var buf = ref.alloc('uint64');
    ref.writeUInt64BE(buf, 0, '18446744073709551615');
    

    ref.writeUInt64LE(Buffer bufferNumber offsetNumber|String input)

    • buffer - The buffer to write to.
    • offset - The offset to begin writing from.
    • input - This String or Number which gets written.

    Writes the input Number or String as a little-endian unsigned 64-bit int into buffer at the given offset.

    var buf = ref.alloc('uint64');
    ref.writeUInt64LE(buf, 0, '18446744073709551615');
    

    ref._attach(Buffer bufferObject|Buffer object)

    • buffer - A Buffer instance to attach object to.
    • object - An Object or Buffer to prevent from being garbage collected until buffer does.

    Attaches object to buffer such that it prevents object from being garbage collected until buffer does.

    ref._reinterpret(Buffer bufferNumber sizeNumber offset→ Buffer

    • buffer - A Buffer instance to base the returned Buffer off of.
    • size - The length property of the returned Buffer.
    • offset - The offset of the Buffer to begin from.
    • Return: A new Buffer instance with the same memory address as buffer, and the requested size.

    Same as ref.reinterpret(), except that this version does not attach buffer to the returned Buffer, which is potentially unsafe if the garbage collector runs.

    ref._reinterpretUntilZeros(Buffer bufferNumber sizeNumber offset→ Buffer

    • buffer - A Buffer instance to base the returned Buffer off of.
    • size - The number of sequential, aligned NULL bytes that are required to terminate the buffer.
    • offset - The offset of the Buffer to begin from.
    • Return: A new Buffer instance with the same memory address as buffer, and a variable length that is terminated by size NUL bytes.

    Same as ref.reinterpretUntilZeros(), except that this version does not attach buffer to the returned Buffer, which is potentially unsafe if the garbage collector runs.

    ref._writeObject(Buffer bufferNumber offsetObject object)

    • buffer - A Buffer instance to write object to.
    • offset - The offset on the Buffer to start writing at.
    • object - The Object to be written into buffer.

    Same as ref.writeObject(), except that this version does not attach the Object to the Buffer, which is potentially unsafe if the garbage collector runs.

    ref._writePointer(Buffer bufferNumber offsetBuffer pointer)

    • buffer - A Buffer instance to write _pointer to.
    • offset - The offset on the Buffer to start writing at.
    • pointer - The Buffer instance whose memory address will be written to buffer.

    Same as ref.writePointer(), except that this version does not attach pointer to buffer, which is potentially unsafe if the garbage collector runs.


    "type" system

    A "type" in ref is simply an plain 'ol JavaScript Object, with a set of expected properties attached that implement the logic for getting & setting values on a given Buffer instance.

    To attach a "type" to a Buffer instance, you simply attach the "type" object to the Buffer's type property. ref comes with a set of commonly used types which are described in this section.

    Creating your own "type"

    It's trivial to create your own "type" that reads and writes your own custom datatype/class to and from Buffer instances using ref's unified API.
    To create your own "type", simply create a JavaScript Object with the following properties defined:

    NameData TypeDescription
    sizeNumberThe size in bytes required to hold this datatype.
    indirectionNumberThe current level of indirection of the buffer. When defining your own "types", just set this value to 1.
    getFunctionThe function to invoke when ref.get() is invoked on a buffer of this type.
    setFunctionThe function to invoke when ref.set() is invoked on a buffer of this type.
    nameString(Optional) The name to use during debugging for this datatype.
    alignmentNumber(Optional) The alignment of this datatype when placed inside a struct. Defaults to the type's size.

    The built-in "types"

    Here is the list of ref's built-in "type" Objects. All these built-in "types" can be found on the ref.types export Object. All the built-in types use "native endianness" when multi-byte datatypes are involved.

    types.void

    The void type.

    types.int8

    The int8 type.

    types.uint8

    The uint8 type.

    types.int16

    The int16 type.

    types.uint16

    The uint16 type.

    types.int32

    The int32 type.

    types.uint32

    The uint32 type.

    types.int64

    The int64 type.

    types.uint64

    The uint64 type.

    types.float

    The float type.

    types.double

    The double type.

    types.Object

    The Object type. This can be used to read/write regular JS Objects into raw memory.

    types.CString

    The CString (a.k.a "string") type.

    CStrings are a kind of weird thing. We say it's sizeof(char *), and indirection level of 1, which means that we have to return a Buffer that is pointer sized, and points to a some utf8 string data, so we have to create a 2nd "in-between" buffer.

    types.bool

    The bool type.

    Wrapper type around types.uint8 that accepts/returns true or false Boolean JavaScript values.

    types.byte

    The byte type.

    types.char

    The char type.

    types.uchar

    The uchar type.

    types.short

    The short type.

    types.ushort

    The ushort type.

    types.int

    The int type.

    types.uint

    The uint type.

    types.long

    The long type.

    types.ulong

    The ulong type.

    types.longlong

    The longlong type.

    types.ulonglong

    The ulonglong type.

    types.size_t

    The size_t type.


    Buffer extensions

    Buffer.prototype gets extended with some convenience functions that you can use in your modules and/or applications.

    Buffer#address()

    Shorthand for ref.address(this, …).

    Accepts a Buffer instance and returns the memory address of the buffer instance.

    console.log(ref.address(new Buffer(1)));
    4320233616
    
    console.log(ref.address(ref.NULL)));
    0
    

    Buffer#deref()

    Shorthand for ref.deref(this, …).

    Accepts a Buffer instance and attempts to "dereference" it. That is, first it checks the indirection count of buffer's "type", and if it's greater than 1 then it merely returns another Buffer, but with one level less indirection.

    When buffer's indirection is at 1, then it checks for buffer.type which should be an Object with its own get() function.

    var buf = ref.alloc('int', 6);
    
    var val = ref.deref(buf);
    console.log(val);
    6
    

    Buffer#hexAddress()

    Shorthand for ref.hexAddress(this, …).

    Buffer#inspect()

    ref overwrites the default Buffer#inspect() function to include the hex-encoded memory address of the Buffer instance when invoked.

    This is simply a nice-to-have.

    Before:

    console.log(new Buffer('ref'));
    <Buffer 72 65 66>
    

    After:

    console.log(new Buffer('ref'));
    <Buffer@0x103015490 72 65 66>
    

    Buffer#isNull()

    Shorthand for ref.isNull(this, …).

    Accepts a Buffer instance and returns true if the buffer represents the NULL pointer, false otherwise.

    console.log(ref.isNull(new Buffer(1)));
    false
    
    console.log(ref.isNull(ref.NULL));
    true
    

    Buffer#readCString()

    Shorthand for ref.readCString(this, …).

    Returns a JavaScript String read from buffer at the given offset. The C String is read until the first NULL byte, which indicates the end of the String.

    This function can read beyond the length of a Buffer.

    var buf = new Buffer('hello\0world\0');
    
    var str = ref.readCString(buf, 0);
    console.log(str);
    'hello'
    

    Buffer#readInt64BE()

    Shorthand for ref.readInt64BE(this, …).

    Returns a big-endian signed 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('int64');
    ref.writeInt64BE(buf, 0, '9223372036854775807');
    
    var val = ref.readInt64BE(buf, 0)
    console.log(val)
    '9223372036854775807'
    

    Buffer#readInt64LE()

    Shorthand for ref.readInt64LE(this, …).

    Returns a little-endian signed 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('int64');
    ref.writeInt64LE(buf, 0, '9223372036854775807');
    
    var val = ref.readInt64LE(buf, 0)
    console.log(val)
    '9223372036854775807'
    

    Buffer#readObject()

    Shorthand for ref.readObject(this, …).

    Reads a JavaScript Object that has previously been written to the given buffer at the given offset.

    var obj = { foo: 'bar' };
    var buf = ref.alloc('Object', obj);
    
    var obj2 = ref.readObject(buf, 0);
    console.log(obj === obj2);
    true
    

    Buffer#readPointer()

    Shorthand for ref.readPointer(this, …).

    Reads a Buffer instance from the given buffer at the given offset. The size parameter specifies the length of the returned Buffer instance, which defaults to 0.

    var buf = new Buffer('hello world');
    var pointer = ref.alloc('pointer');
    
    var buf2 = ref.readPointer(pointer, 0, buf.length);
    console.log(buf.toString());
    'hello world'
    

    Buffer#readUInt64BE()

    Shorthand for ref.readUInt64BE(this, …).

    Returns a big-endian unsigned 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('uint64');
    ref.writeUInt64BE(buf, 0, '18446744073709551615');
    
    var val = ref.readUInt64BE(buf, 0)
    console.log(val)
    '18446744073709551615'
    

    Buffer#readUInt64LE()

    Shorthand for ref.readUInt64LE(this, …).

    Returns a little-endian unsigned 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('uint64');
    ref.writeUInt64LE(buf, 0, '18446744073709551615');
    
    var val = ref.readUInt64LE(buf, 0)
    console.log(val)
    '18446744073709551615'
    

    Buffer#ref()

    Shorthand for ref.ref(this, …).

    ref() accepts a Buffer instance and returns a new Buffer instance that is "pointer" sized and has its data pointing to the given Buffer instance. Essentially the created Buffer is a "reference" to the original pointer, equivalent to the following C code:

    char *buf = buffer;
    char **ref = &buf;
    

    Buffer#reinterpret()

    Shorthand for ref.reinterpret(this, …).

    Returns a new Buffer instance with the specified size, with the same memory address as buffer.

    This function "attaches" buffer to the returned Buffer to prevent it from being garbage collected.

    Buffer#reinterpretUntilZeros()

    Shorthand for ref.reinterpretUntilZeros(this, …).

    Accepts a Buffer instance and a number of NULL bytes to read from the pointer. This function will scan past the boundary of the Buffer's length until it finds size number of aligned NULL bytes.

    This is useful for finding the end of NUL-termintated array or C string. For example, the readCString() function could be implemented like:

    function readCString (buf) {
      return ref.reinterpretUntilZeros(buf, 1).toString('utf8')
    }
    

    This function "attaches" buffer to the returned Buffer to prevent it from being garbage collected.

    Buffer#writeCString()

    Shorthand for ref.writeCString(this, …).

    Writes the given string as a C String (NULL terminated) to the given buffer at the given offset. "encoding" is optional and defaults to 'utf8'.

    Unlike readCString(), this function requires the buffer to actually have the proper length.

    Buffer#writeInt64BE()

    Shorthand for ref.writeInt64BE(this, …).

    Writes the input Number or String as a big-endian signed 64-bit int into buffer at the given offset.

    var buf = ref.alloc('int64');
    ref.writeInt64BE(buf, 0, '9223372036854775807');
    

    Buffer#writeInt64LE()

    Shorthand for ref.writeInt64LE(this, …).

    Writes the input Number or String as a little-endian signed 64-bit int into buffer at the given offset.

    var buf = ref.alloc('int64');
    ref.writeInt64LE(buf, 0, '9223372036854775807');
    

    Buffer#writeObject()

    Shorthand for ref.writeObject(this, …).

    Writes a pointer to object into buffer at the specified _offset.

    This function "attaches" object to buffer to prevent it from being garbage collected.

    var buf = ref.alloc('Object');
    ref.writeObject(buf, 0, { foo: 'bar' });
    

    Buffer#writePointer()

    Shorthand for ref.writePointer(this, …).

    Writes the memory address of pointer to buffer at the specified offset.

    This function "attaches" object to buffer to prevent it from being garbage collected.

    var someBuffer = new Buffer('whatever');
    var buf = ref.alloc('pointer');
    ref.writePointer(buf, 0, someBuffer);
    

    Buffer#writeUInt64BE()

    Shorthand for ref.writeUInt64BE(this, …).

    Writes the input Number or String as a big-endian unsigned 64-bit int into buffer at the given offset.

    var buf = ref.alloc('uint64');
    ref.writeUInt64BE(buf, 0, '18446744073709551615');
    

    Buffer#writeUInt64LE()

    Shorthand for ref.writeUInt64LE(this, …).

    Writes the input Number or String as a little-endian unsigned 64-bit int into buffer at the given offset.

    var buf = ref.alloc('uint64');
    ref.writeUInt64LE(buf, 0, '18446744073709551615');
    

    展开全文
  • 在react开发过程中,有时会碰到一些需求需要我们去操控dom,那么我们就可以给组件挂载一个ref属性,然后就可以通过ref调用这个组件的方法或者属性之类的。 接下来我们就来看看函数组件和类组件都是如何去挂载创建ref...

    在react开发过程中,有时会碰到一些需求需要我们去操控dom,那么我们就可以给组件挂载一个ref属性,然后就可以通过ref调用这个组件的方法或者属性之类的。

    接下来我们就来看看函数组件和类组件都是如何去挂载创建ref和使用它的:

    函数式组件(Hook):
    // 首先引入React及useRef
    import React, { useRef } from 'react;
    function Content() {
    	// 创建ref
    	const fileInputEl = useRef(null);
    	return (
    		<>
    			{/* 在你的元素或者组件上面挂载ref */}
    			<input ref={fileInputEl} type={'file'} hidden />
    			{/* 使用ref */}
    			{/* 当点击这个div的时候触发input的点击事件 */}
    			<div onClick={() => fileInputEl.current.click()}>上传文件</div>
    		</>
    	)
    }
    

    类组件创建使用ref
    // 引入React
    import React, { Component } from 'react';
    export default class Content extends Component {
    	constructor(props) {
    		super(props);
    		// 通过React.createRef()创建ref,挂载到组件上
    		this.editTableEl = React.createRef();
    	}
    	componentWillReceiveProps() {
    		// 当走入componentWillReceiveProps生命周期时会触发此ref挂载到的组件的refreshDataSource()方法(PS:这个方法是自己在挂载ref的那个组件中定义的)
    		this.editTableEl.current && this.editTableEl.current.refreshDataSource();
    	}
    	render() {
    		return (
    			<div>
    				<EditableTable
    					// 挂载ref
    					ref={this.editTableEl}
    				/>
    			</div>
    		)
    	}
    }
    
    展开全文
  • vue中的ref

    2017-10-23 15:59:10
    ref

    如果consoe.log(this.$refs.wrapper)打印出来的是undefined,那么就页面多刷新几次,
    因为ref不是响应式的

    注意event.currentTarget.refsundefinedrefs只对this起作用

    注意:在vue的项目中尽量不要用DOM去操作元素,不然在渲染页面的时候会出问题(尤其是通过数据和索引之间的值来控制页面切换的时候),尽量用this.$refs.wrapper去操作。

    展开全文
  • Vue与ref属性与refs

    万次阅读 多人点赞 2018-05-25 18:31:04
    ref 被用来给DOM元素或子组件注册引用信息。引用信息会根据父组件的 $refs 对象进行注册。如果在普通的DOM元素上使用,引用信息就是元素; 如果用在子组件上,引用信息就是组件实例注意:只要想要在Vue中直接操作DOM...

    ref 被用来给DOM元素或子组件注册引用信息。引用信息会根据父组件的 $refs 对象进行注册。如果在普通的DOM元素上使用,引用信息就是元素; 如果用在子组件上,引用信息就是组件实例

    注意:只要想要在Vue中直接操作DOM元素,就必须用ref属性进行注册

    这里写图片描述

    实例:

    这里写图片描述

    这里写图片描述

    这里为了在create的时候引用DOM元素,先在DOM中使用ref标签进行了注册,然后便可以通过’this.$refs’再跟注册时的名称来引用DOM元素了

    第二部分

    vue中的 ref 和 $refs

    如图,ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例:

    在上面的例子中,input的引用信息为input1 ,$refs 是所有注册过的ref的一个集合,

    console.log(this.$refs.input1)//<input type="text" id="input1">
    console.log(document.getElementById('input1'))//<input type="text" id="input1">

     这两种方法获得的都是Dom节点,而$refs相对document.getElementById的方法,会减少获取dom节点的消耗。

    ref和v-for在一起的情况

    li里的ref的无法读取item里面的值,即item.name或被直接读取为字符串“item.name”,

    此时的$refs

     第三部分:

    一、ref使用在外面的组件上

    HTML 部分

    <div id="ref-outside-component" v-on:click="consoleRef">
        <component-father ref="outsideComponentRef">
        </component-father>
        <p>ref在外面的组件上</p>
    </div>
    

    js部分

        var refoutsidecomponentTem={
            template:"<div class='childComp'><h5>我是子组件</h5></div>"
        };
        var  refoutsidecomponent=new Vue({
            el:"#ref-outside-component",
            components:{
                "component-father":refoutsidecomponentTem
            },
            methods:{
                consoleRef:function () {
                    console.log(this); // #ref-outside-component     vue实例
                    console.log(this.$refs.outsideComponentRef);  // div.childComp vue实例
                }
            }
        });
    

    二、ref使用在外面的元素上

    HTML部分

    <!--ref在外面的元素上-->
    <div id="ref-outside-dom" v-on:click="consoleRef" >
       <component-father>
       </component-father>
       <p  ref="outsideDomRef">ref在外面的元素上</p>
    </div>
    

    JS部分

       var refoutsidedomTem={
            template:"<div class='childComp'><h5>我是子组件</h5></div>"
        };
        var  refoutsidedom=new Vue({
            el:"#ref-outside-dom",
            components:{
                "component-father":refoutsidedomTem
            },
            methods:{
                consoleRef:function () {
                    console.log(this); // #ref-outside-dom    vue实例
                    console.log(this.$refs.outsideDomRef);  //   <p> ref在外面的元素上</p>
                }
            }
        });
    

    三、ref使用在里面的元素上---局部注册组件

    HTML部分

    <!--ref在里面的元素上-->
    <div id="ref-inside-dom">
        <component-father>
        </component-father>
        <p>ref在里面的元素上</p>
    </div>
    

    JS部分

        var refinsidedomTem={
            template:"<div class='childComp' v-on:click='consoleRef'>" +
                           "<h5 ref='insideDomRef'>我是子组件</h5>" +
                      "</div>",
            methods:{
                consoleRef:function () {
                    console.log(this);  // div.childComp   vue实例 
                    console.log(this.$refs.insideDomRef);  // <h5 >我是子组件</h5>
                }
            }
        };
        var  refinsidedom=new Vue({
            el:"#ref-inside-dom",
            components:{
                "component-father":refinsidedomTem
            }
        });
    

    四、ref使用在里面的元素上---全局注册组件

    HTML部分

    <!--ref在里面的元素上--全局注册-->
    <div id="ref-inside-dom-all">
        <ref-inside-dom-quanjv></ref-inside-dom-quanjv>
    </div>
    

    JS部分

        Vue.component("ref-inside-dom-quanjv",{
            template:"<div class='insideFather'> " +
                        "<input type='text' ref='insideDomRefAll' v-on:input='showinsideDomRef'>" +
                        "  <p>ref在里面的元素上--全局注册 </p> " +
                      "</div>",
            methods:{
                showinsideDomRef:function () {
                    console.log(this); //这里的this其实还是div.insideFather
                    console.log(this.$refs.insideDomRefAll); // <input  type="text">
                }
            }
        });
    
        var refinsidedomall=new Vue({
            el:"#ref-inside-dom-all"
        });



    展开全文
  • vue ref :refIn my previous post, I implemented my first Vue3 component. 在上一篇文章中,我实现了我的第一个Vue3组件。 I implementend a very simple web app (roll the dice) where I had a “div” where ...
  • vue中ref

    千次阅读 2019-11-28 12:15:37
    vue中ref
  • Spring中引用标签ref和属性ref

    万次阅读 2017-12-15 14:21:53
    Spring中ref标签和ref属性的区别,如何正确的使用它们。
  • ref cursor

    千次阅读 2011-12-03 21:44:06
    利用REF CURSOR,可以在程序间传递结果集(一个程序里打开游标变量,在另外的程序里处理数据)。也可以利用REF CURSOR实现BULK SQL,提高SQL性能。 REF CURSOR分两种,Strong REF CURSOR 和 Weak REF CURSOR。 ...
  • vue3.0 ref

    千次阅读 2020-07-25 16:28:55
    import { ref } from 'vue' setup(){ const xx =ref(初始值) (1)调用 xx.value (2)自动解套(即不需要xx.value获取值) 1、在setup的return{xx}中,在template中直接{{xx}} 2、在...
  • 1、动态添加ref: <li v-for="(item, index) in dataList" :ref="`program${index}`" @click="checkLog(index)"></li> 2、通过ref设置li的背景颜色 checkLog(index){ for(let i = 0; i < this....
  • Vue教程(ref和$refs的使用)

    万次阅读 多人点赞 2019-08-02 17:55:08
      在Vue中一般很少会用到直接操作DOM,但不可避免有时候需要用到,这时我们可以通过ref和$refs这两个来实现,本文我们就来详细的介绍下这个内容 ref    ref 被用来给元素或子组件注册引用信息, 引用信息将会...
  • C#中关键字ref和out

    千次阅读 2021-03-24 11:25:30
    ref ref:MSDN的定义为:“The ref keyword indicates a value that is passed by reference.”就是通过引用来传递参数。ref也是Reference的缩写。 不使用ref using System; namespace Test_Code { class A { ...
  • Vue3学习笔记--ref以及ref相关函数

    千次阅读 2020-10-27 14:58:38
    在Vue2.x通过给元素添加ref=‘xxx’,,然后使用refs.xxx的方式来获取元素 在Vue3.x中我们也可以通过ref来获取元素 用法 创建变量 import { ref } from 'vue' const count = ref(0) console.log(coun
  • ref标签和ref属性区别
  • VUE ref 属性

    2019-04-02 00:31:27
    如果给标签绑定ref='xxx’属性,使用 this.$refs.xxx获取原生的jsDom对象 ref属性值不能重名 如果是给组件绑定ref属性,那么this.$ref.xxx 获取的是当前的组件对象 我是按钮1 我是按钮2 ...
  • Spring的ref bean和ref local

    千次阅读 2015-03-23 14:50:44
    ref bean<ref bean="someBean"/>可以引用运行容器中的bean的id或name。既包括当前环境,也包括父级环境中的bean。参见。ref local<ref local="someBean"/>只能引用当前xml中配置的bean的id,不能是name。运行前就...
  • fatal: update_ref failed for ref ‘ORIG_HEAD’: cannot lock ref ‘ORIG_HEAD’: unable to resolve reference ‘ORIG_HEAD’: reference broken 进入.git文件夹发现了ORIG_HEAD这个文件 将这个文件删除,然后...
  • vue动态绑定ref(使用变量)以及获取

    万次阅读 多人点赞 2019-11-04 09:47:09
    正常情况,我们需要在vue中获得某个dom或者组件,我们会通过绑定 ref 然后通过绑定后的名字来获取这个dom 。 但是,如果我们在v-for中绑定ref的话,那么这个ref就会存在多个,比如我们点击事件让对应的显示/隐藏的...
  • ref值重复,如何获取对应标签或组件 正常使用vue 的 ref属性时 使用$refs获取返回的是一个对象,对象包含组件内部信息.(例如 method中方法,及data中数据) //gauge 组件内部定义了个方法fun; <gauge :dataSource...
  • vue 3.0 使用ref获取dom元素

    万次阅读 热门讨论 2020-09-24 16:00:52
    div ref="myRef"></div> this.$refs.myRef Vue 3.0获取DOM <template> <div :ref="setRef">获取DOM元素</div> </template> <script> import { nextTick } from 'vue'; ...
  • react 使用ref

    2018-07-19 14:15:50
    react中ref这样的用法已经是很落后的了(在react中不要轻易的使用ref除了一些表单、动画、多媒体一些特殊需求外,要有一个明确的态度能不用ref的就不要用) 用新方法 可以定义一个全局变量  var content ; &...
  • vue中ref标签属性和$ref的关系,

    千次阅读 2019-09-28 18:13:08
    Vue给我们提供了一个专门用来获取DOM节点的方法 ,使用元素的ref属性,使用起来非常方便 (这只是用于偶尔vue需要操作节点时候才使用) vue的ref属性 ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件...
  • 总结ref的用法

    2020-09-07 15:04:15
    ref通常被用来获取DOM元素或组件实例 string类型的ref <input type='text' ref='input' /> ...... console.log(this.$refs.input) // <input type='text' /> $refs 是所有注册过的ref的一个集合 在...
  • git cannot lock ref

    千次阅读 2018-01-31 09:17:14
    cannot lock ref ‘refs/remotes/origin/xx’:’refs/remotes/origin/xx/xx’ exists cannot create ‘ref/remotes/origin/xx’ 那么请看本文,本文提供了一个解决方法。 请使用下面代码 git update-ref -d ...
  • eq_ref>ref>range>index>all) 1、const:查询索引字段,并且表中最多只有一行匹配(好像只有主键查询只匹配一行才会是const,有些情况唯一索引匹配一行会是ref) 2、eq_ref 主键或者唯一索引 3、ref 非...
  • hook中ref使用

    千次阅读 2019-05-30 17:44:00
    hook使用ref 父组件: 引入 useRef 声明ref的名字 const dateRef = useRef() 复值给组件 ref={dateRef} 使用 dateRef...
  • Mysql执行计划中eq_refref类型的区别

    千次阅读 2020-08-25 17:08:34
    eq_ref - 想象你有两张桌子。表A包含列(id,text),其中id是主键。表B具有相同的列(id,text),其中id是主键。表A包含以下数据: 1, Hello 2, How are 表B有以下数据: 1, world! 2, you? 想象一下eq_ref为A和B...
  • C#中ref和out有什么区别?ref是引用么? C#中ref和out有什么区别?ref是引用么?

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 115,059
精华内容 46,023
关键字:

ref