Does Dart provide any form of memcpy-like functions? I'd like to do a shallow copy of one object's data to the address of another:
var foo = Foo("hi");
var bar = Foo("hello");
memcpy(&foo, &bar, sizeof(Foo));
Does Dart provide any form of memcpy-like functions? I'd like to do a shallow copy of one object's data to the address of another:
var foo = Foo("hi");
var bar = Foo("hello");
memcpy(&foo, &bar, sizeof(Foo));
No.
Dart does not allow you access to memory as such, and it has no way to shallow-copy an object without the class cooperating.
If you want to copy an object, you must create a new object using a constructor and have it fill in the fields. Dart constructors can do anything, and some classes are built in a way where they depend on a constructor maintaining some coherent global state. For example, a class could assign consecutive IDs to its objects by initializing a field with final int id = _staticCounter++;
. Copying that object would break the invariant that all objects have different IDs.
There is no known workaround for a shallow copy.
For a deep copy, there is one hack that gets around this. If your platform supports dart:isolate
, you can send an object to yourself:
import "dart:mirrors";
Future<T> clone<T>(T value) {
return (ReceivePort()..sendPort.send(value)).first;
}
Not all values can be sent through a send-port. Not all classes will work correctly for objects not created using constructors.