Equivalent of C++'s reinterpret_cast in C#
This works. And yes, it's as evil and as awesome as you can possibly imagine.
static unsafe TDest ReinterpretCast<TSource, TDest>(TSource source)
{
var sourceRef = __makeref(source);
var dest = default(TDest);
var destRef = __makeref(dest);
*(IntPtr*)&destRef = *(IntPtr*)&sourceRef;
return __refvalue(destRef, TDest);
}
One thing to note is that if you're casting a T[]
to and U[]
:
- If
T
is bigger thanU
, the bounds-checking will prevent you from accessing theU
elements past the original length of theT[]
- If
T
is smaller thanU
, the bounds-checking will let you read past the last element (effectively its a buffer overrun vulnerability)
discussion
As some of the answers point out, .Net is enforcing type safety rigorously in the question's scope. A reinterpret_cast
would be an inherently unsafe operation, hence the possible ways to implement one would be either through reflection or serialization, whereas the two are related.
As you mentioned in an update, a possible use could be an RPC framework. RPC libraries typically use serialization/reflection anyway, and there are a couple of usable ones:
- protobuf-remote
- msgpack-rpc-cli
so, you might not want to write one yourself, perhaps.
If your class Base
would use public properties, you could use AutoMapper:
class Base
{
public int Counter { get; set; }
// ...
}
...
AutoMapper.Mapper.CreateMap<Base, Foo>();
Foo foo = AutoMapper.Mapper.Map<Foo>(b);
Where Foo
need not be derived from Base
at all. It just has to have the property you are interested in mapping onto. But again, you might not need two types at all - a rethinking of the architecture might be the solution.
Typically, there is no need to use reinterpret_cast
, by way of a clean architecture that fits nicely into the patterns used in the .Net Framework. If you still insist on having something like that, here's a solution using the compact serialization library protobuf-net.
serialization solution
Your classes:
using System;
using System.IO;
using ProtoBuf;
using ProtoBuf.Meta;
[ProtoContract]
[ProtoInclude(3, typeof(Foo))]
class Base
{
[ProtoMember(1)]
protected int counter = 0;
public Base(int c) { counter = c; }
public Base() { }
}
[ProtoContract]
class Foo : Base
{
public int Counter { get { return counter; } }
}
and a runnable serialization-deserialization example:
class Program
{
static void Main(string[] args)
{
Base b = new Base(33);
using (MemoryStream stream = new MemoryStream())
{
Serializer.Serialize<Base>(stream, b);
Console.WriteLine("Length: {0}", stream.Length);
stream.Seek(0, SeekOrigin.Begin);
Foo f=new Foo();
RuntimeTypeModel.Default.Deserialize(stream, f, typeof(Foo));
Console.WriteLine("Foo: {0}", f.Counter);
}
}
}
outputting
Length: 2
Foo: 33
If you don't want to declare derived types in your contract, see this example...
As you see, the serialization is extremely compact.
If you want to use more fields, you might try implicit serialization of fields:
[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
A generic reinterpret_cast
might definitely be possible to implement either via this serialization solution, or directly via reflection, but I wouldn't invest the time at the moment.
You might be able to achieve similar behavior with unsafe
blocks and void*
in C#:
unsafe static TResult ReinterpretCast<TOriginal, TResult>(this TOriginal original)
where TOriginal : struct
where TResult : struct
{
return *(TResult*)(void*)&original;
}
Usage:
Bar b = new Bar();
Foo f = b.ReinterpretCast<Foo>();
f = ReinterpretCast<Foo>(b); // this works as well
Not tested.
The struct constraints nullify the point of your question, I guess, but they're necessary since classes are managed by the GC so you're not allowed to have pointers to them.