Reputation: 123
Is there any way, how to convert this:
namespace Library
{
public struct Content
{
int a;
int b;
}
}
I have struct in Library2.Content that has data defined same way
({ int a; int b; }
), but different methods.
Is there a way to convert a struct instance from Library.Content to Library2.Content? Something like:
Library.Content c1 = new Library.Content(10, 11);
Library2.Content c2 = (Libary2.Content)(c1); //this doesn't work
Upvotes: 8
Views: 14264
Reputation: 91
A bit late to the game. But if the structs match I used this in the past
public static object CastTo(ref object obj, Type type)
{
var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(type));
try
{
Marshal.StructureToPtr(obj, ptr, false);
return Marshal.PtrToStructure(ptr, type);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
Thanks to @avi_sweden for pointing out that the allocated memory should be freed
Upvotes: 1
Reputation: 178650
You have several options, including:
Library2.Content
and pass in the values of your Library.Content
to the constructor.Upvotes: 13
Reputation: 160862
Just for completeness, there is another way to do this if the layout of the data types is the same - through marshaling.
static void Main(string[] args)
{
foo1 s1 = new foo1();
foo2 s2 = new foo2();
s1.a = 1;
s1.b = 2;
s2.c = 3;
s2.d = 4;
object s3 = s1;
s2 = CopyStruct<foo2>(ref s3);
}
static T CopyStruct<T>(ref object s1)
{
GCHandle handle = GCHandle.Alloc(s1, GCHandleType.Pinned);
T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return typedStruct;
}
struct foo1
{
public int a;
public int b;
public void method1() { Console.WriteLine("foo1"); }
}
struct foo2
{
public int c;
public int d;
public void method2() { Console.WriteLine("foo2"); }
}
Upvotes: 12
Reputation: 22210
You could define an explicit conversion operator inside Library2.Content
as follows:
// explicit Library.Content to Library2.Content conversion operator
public static explicit operator Content(Library.Content content) {
return new Library2.Content {
a = content.a,
b = content.b
};
}
Upvotes: 5