BlockLeftTop, PRELOAD BlockLeftBottom, PRELOAD BlockLeftStretch, PRELOAD BlockTop, PRELOAD BlockBottom, PRELOAD BlockStretch, PRELOAD BlockRightTop, PRELOAD BlockRightBottom, PRELOAD BlockRightStretch, PRELOAD
DeltaEngine

Cute little trick to share memory of C# structs (e.g. with Vector3)

by Benjamin Nitschke 2. November 2009 02:41

C# Union

We recently had the problem that we want to share some structs we wrote with other structs in other assemblies. For example we cannot change XNA Vector3 (well, its not open source) and even an open source Vector3 like the one from OpenTK should not be changed, we just want to use the libraries. However, if you start using an XNA Vector in some class and then decide you want to switch to OpenTK, you kinda have a problem. The data is EXACTLY the same: X, Y and Z, thats it! Just 3 floats, but many different structs that describe them and have different methods for manipulating them. If you are only using XNA or only OpenTK, then there is no problem, except maybe when you want to extend the given Vector3 struct from the framework/library you are using. Then you might introduce a Vector3Helper class like I did in almost all my XNA projects, which is kinda ugly too.


Our engine however is going to support many frameworks and libraries, and not only that, it is easily extensible and totally customizable. We do not enforce to use XNA or OpenTK or whatever else, it is all a choice of the programmer, whatever he needs. To accomplish this I today present a very little cute trick on how to merge all those structs together and make them easily extensible: Yes, you can add methods to exsting structs without any helper classes!


The magic word is: Union. Now you might say: Wait a second, C++ has unions, but C# does not have them and using pointers is also no fun in C#. Well, you still can use the StructLayout(LayoutKind.Explicit) attribute and then the FieldOffset(0) attribute to mark overlapping memory regions. Just add all the structs (since they are value types and have the sequential x, y, z data there are all the same) and then define x, y and z yourself and use whatever vector you want. Our implementation works a little different because the use of XNA or OpenTK is optional (Tip: Did you know that you can have partial structs? They are fun ^^), but the overall idea is very much the same. I present you the Vector3 struct with XNA and OpenTK support all in one:

 


	/// 
	/// Class with own Vector3 functionality, but still using the same shared
	/// memory as Vector3 does. This not only means we get all the XNA Vector3
	/// (and any other Vector3 we plug in here) functionality for free, but
	/// we can also mix the data types as much as we want (e.g. just set
	/// the xnaVector and all the other vectors are set automatically for us).
	/// 
	[StructLayout(LayoutKind.Explicit)]
	public struct Vector3
	{
		#region Shared vectors (XNA, OpenTK, and our own data)
		// First setup the shared vector structs. Start with an XNA Vector.
		// Note: This could also be private if you want to hide this from the
		// Vector3 users!
		[FieldOffset(0)]
		public Microsoft.Xna.Framework.Vector3 xnaVector;
		// Same with OpenTK.Vector3
		[FieldOffset(0)]
		public OpenTK.Vector3 openTkVector;

		// And then the same data again just as we want to use it! Start with x.
		[FieldOffset(0)]
		public float x;
		// Da Y coordinate
		[FieldOffset(4)]
		public float y;
		// And finally the z coordinate!
		[FieldOffset(8)]
		public float z;

		//Note: This won't work, it would make x, y AND z all start at offset 0!
		//[FieldOffset(0)]
		//public float x, y, z;
		#endregion

		// Go ahead with our constructors, methods, etc.
		// Note: We can easily use the XNA or OpenTK functionality here.
	} // struct Vector3

 

And finally some testing code to prove this actually works (this is just some copied code from our early unit tests, I just added some Console.WriteLine code lines):

 


			// Create a simple vector that happend to have the length 5 (3*3+4*4=25)
			Vector3 vector = new Vector3 { x = 0, y = 3, z = 4 };
			Console.WriteLine("vector=" + vector);
			Console.WriteLine("vector.x=" + vector.x);
			Console.WriteLine("vector.y=" + vector.y);
			Console.WriteLine("vector.z=" + vector.z);

			// Sadly xnaVector and vector are not the same by default :(
			// We could easily add operators to support comparing these too,
			// but for now we should try to use Vector3 exclusively.
			//does not compile: Assert.Equal(vector, vector.xnaVector);
			Console.WriteLine("XNA vector=" + vector.xnaVector);
			Console.WriteLine("OpenTK vector=" + vector.xnaVector);

			// Lets play around with xnaVector and openTkVector
			// First use an XNA method
			//Assert.Equal(5, vector.xnaVector.Length());
			Console.WriteLine("XNA vector length=" + vector.xnaVector.Length());
			// Next try an OpenTK method
			//Assert.Equal(5, vector.openTkVector.Length);
			Console.WriteLine("OpenTK vector length=" + vector.openTkVector.Length);

			// Do a more complicated test, add another XNA vector and then
			// check if the OpenTK vector is also updated.
			Vector3 anotherVector = new Vector3 { x = 0, y = 3, z = -4 };
			// Note: We don't have our own + operator yet, just use the one from XNA
			vector.xnaVector += anotherVector.xnaVector;
			// Finally check if our new vector is 0, 6, 0 now!
			Console.WriteLine("XNA vector+anotherVector=" + vector.xnaVector);
			Console.WriteLine("OpenTK vector+another length=" +
				vector.openTkVector.Length);

Comments


11/17/2009 2:19:52 PM #

Nohing important but to be correct :

the line :
13.Console.WriteLine("OpenTK vector=" + vector.xnaVector);

should be :
13.Console.WriteLine("OpenTK vector=" + vector.openTkVector);

cheers,
Hans

Hans Hamm | Reply



11/19/2009 3:33:53 PM #

Hmmm interesting stuff

payday loans | Reply



12/28/2009 6:33:28 PM #



Hmmm interesting stuff

auto insurance quotes | Reply



1/7/2010 10:08:20 PM #

I like what I see. keep it going

payday loans | Reply



1/10/2010 2:47:13 PM #

I like what I see. keep it going

guaranteed personal loans | Reply



1/12/2010 8:55:09 PM #

Interesting post

Rhode Island Personal Loans | Reply



1/15/2010 11:46:18 AM #

This topic has been up for debate quite a lot of times but none of the posts were as detailed as yours. I hope to see This topic has been up for debate quite a lot of times but none of the posts were as detailed as yours. I hope to see such quality posts from you in the future.

Annuities | Reply



1/15/2010 1:17:51 PM #

This article gives the light in which we can observe the reality. this is very nice one and gives indepth information.

pension annuities | Reply



1/16/2010 3:27:30 PM #

Admiring the time and effort you put into your blog and detailed information you offer! I will bookmark your blog and have my children check up here often. Thumbs up!

Contextual link building | Reply



1/18/2010 11:10:51 AM #

I have really enjoyed reading your blog posts.I am looking forward to another great articles from you

Free Mp3 Downloads | Reply



1/20/2010 9:15:20 AM #

nice...interesting stuff

skin firming cream | Reply



1/20/2010 10:44:25 AM #

I enjoyed every little bit of it and I have you bookmarked to check out new stuff you post.Really nice blog to visit...

free games online | Reply



1/21/2010 12:58:00 PM #


This blog is very educative,the  posts are also educative too.
thanks very much.I will tell my friends about it so that they can come
and read this educative articles too.

Best Electronic Cigarette Reviews | Reply



1/22/2010 12:29:38 PM #

this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate a lot and never seem to get something done.

otoplasty | Reply



1/27/2010 8:47:20 AM #

To accomplish this I today present a very little cute trick on how to merge all those structs together and make them easily extensible: Yes, you can add methods to exsting structs without any helper classes!

teak garden furniture | Reply



1/27/2010 12:30:05 PM #

Our engine however is going to support many frameworks and libraries, and not only that, it is easily extensible and totally customizable.

oak furniture | Reply



1/28/2010 9:40:11 AM #

This article gives the light in which we can observe the reality.I enjoyed every little bit of it and I have you bookmarked to check out new stuff you post.

Dating Chat Rooms | Reply



1/29/2010 8:47:27 PM #

Those who insult others are usually describing themselves.

payday loans | Reply



2/1/2010 11:53:43 AM #

This is a cool screen idea ! It is very interesting indeed.Thank you for your info.i love to read all info.This article gives the light in which we can observe the reality.

Apex Professionals LLC | Reply



2/2/2010 12:00:29 PM #

How long have you been in this field? You seem to know a lot more than I do, I’d love to know your sources!

Life insurance | Reply



2/2/2010 12:56:00 PM #

Hi,

Awesome tips. I’ll be passing this post on for sure....

hardwood floors | Reply



2/4/2010 9:05:19 AM #

I will keep visiting this blog very often.It is good to see you verbalise from the heart and your clarity on this important subject can be easily observed.

Plastic Surgery | Reply



2/4/2010 11:38:49 AM #

Cheers to the author for giving me some solid ideas

car finance sydney | Reply



2/4/2010 12:33:42 PM #

Why didn’t I find this post earlier? Keep up the good work!

SEO | Reply



2/4/2010 12:34:57 PM #

Starting to understand a bit more now... Thanks for keeping it simple!

SEO | Reply



2/4/2010 1:03:37 PM #

Really appreciate this post. It’s hard to sort the good from the bad sometimes, but I think you’ve nailed it!

Debt consolidation | Reply



2/8/2010 5:43:27 AM #

Hi,
  Awesome post! Interesting info to know.

internet dating | Reply



2/8/2010 7:01:47 PM #

Saving some memory is a cool thing considering the improvement on speed.

SEO Video Marketing | Reply



2/12/2010 6:58:17 AM #

Great blog post. It’s useful information.

overseas removals | Reply



2/16/2010 11:03:07 AM #

If we wait for the moment when everything, absolutely everything is ready, we shall never begin.

Adult Novelties | Reply



2/17/2010 3:01:43 PM #

Easy code to use,thanks for the share

cheap auto insurance quote  | Reply



2/18/2010 11:59:42 AM #

This article gives the light in which we can observe the reality. this is very nice one and gives indepth information.

easybookmark | Reply



2/22/2010 8:52:45 AM #

This article gives the light in which we can observe the reality.I enjoyed every little bit of it and I have you bookmarked to check out new stuff you post.

Link building campaign | Reply



2/23/2010 3:49:37 PM #

To accomplish this I today present a very little cute trick on how to merge all those structs together and make them easily extensible: Yes, you can add methods to exsting structs without any helper classes!

rocket spanish | Reply



2/24/2010 8:33:22 AM #

Hi,
  A good read, definitely worth a cut and paste. Thanks!

approaching women | Reply



2/25/2010 7:52:32 AM #

Thanks for the blog post! Thats really very nice blog, I am impressed.

Vektorgrafik erstellen | Reply



2/25/2010 10:02:35 AM #

thanks

lelsie | Reply



2/25/2010 8:43:52 PM #

I will keep visiting this blog very often.It is good to see you verbalise from the heart and your clarity on this important subject can be easily observed.

raster icons | Reply



3/8/2010 11:18:24 AM #

You really know your stuff... Keep up the good work!

seo | Reply



3/9/2010 8:04:35 AM #

Really appreciate this post. It’s hard to sort the good from the bad sometimes, but I think you’ve nailed it!

australian employment | Reply



3/10/2010 10:50:05 AM #

Interesting post and I really like your take on the issue.  I now have a clear idea on what this matter is all about. Thank you so much.

window replacement cost Allentown | Reply



3/12/2010 8:39:55 PM #

This sure is a fun and enjoyable site for game geeks.

Amanda | Reply



3/13/2010 11:22:45 AM #

You really know your stuff... Keep up the good work!

administration job | Reply



3/15/2010 9:14:11 AM #

I’m new to blogging. I admire what you have done here. It is good to see your clarity on this important subject can be easily observed.

Thanks

SEO SERVICES | Reply



3/22/2010 8:08:33 AM #

hi.......
Great post! Thanks for the information

Custom stickers | Reply



3/22/2010 9:06:32 AM #

I agree with the positive feedback here.

how to bet on sports | Reply



3/25/2010 11:09:26 PM #

The only place you'll find success before work is in the dictionary.

natural cleaner | Reply



3/31/2010 5:31:31 AM #

I knew the format change was coming, just didn't know when.

Most readers know that I believe the quality of the commenters here is what distinguishes On the Ball from most other sites. It is something I cherish and will work to retain.

Los Angeles Internet Marketing | Reply



4/1/2010 11:14:10 AM #

One must learn by doing the thing. For though you think you know it, you have no certainty until you try.

alta white teeth whitening | Reply



4/6/2010 4:29:45 AM #

It’s hard to sort the good from the bad sometimes, but I think you’ve nailed it!

Search Engine Optimization Services | Reply



4/6/2010 4:02:07 PM #

I would like to say this is an excellent blog that I have ever come across. Very informative. Please write more so that we can get more details.

notebook | Reply



4/15/2010 12:07:29 PM #

Taking all the mentioned above things, I can truly tell that your blog will get great profits.  

flex programming | Reply



4/15/2010 12:09:07 PM #

Hoping for a good change, that would be great if you could provide me with plugins from your blog.

flex programming | Reply



4/17/2010 10:38:11 AM #

Excellent blog post, I look forward to reading more.

overseas removals | Reply



4/17/2010 10:38:34 AM #

You really know your stuff... Keep up the good work!

promotional flash drives | Reply



4/17/2010 10:41:33 AM #

Great post! Thanks for the information

auctions online | Reply



4/17/2010 10:42:06 AM #

Don’t stop blogging! It’s nice to read a sane commentary for once

laptop  | Reply



4/18/2010 1:28:50 PM #

Very useful info. Hope to see more posts soon!

us | Reply



4/20/2010 7:09:17 AM #

I like it very much especially the information you have putted here is like training. Keep the blog up to date. Thanks a lot.

wholesale | Reply



4/20/2010 8:03:23 AM #

Very useful info. Hope to see more posts soon!

business coupon | Reply



4/20/2010 8:03:51 AM #

Sensational info. I look forward to seeing more.

business opportunities | Reply



4/22/2010 3:50:18 AM #

one day i went shopping outside,and in an ed hardy store,I found some kinds of ed hardy i love most they are Your website is really good Thank you for the information

ed hardy | Reply



4/23/2010 7:34:57 PM #

Happiness is the sense that one matters.

cash advance | Reply


4/26/2010 8:10:46 AM #

Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information.

Mortgage Colorado | Reply




4/26/2010 11:32:20 AM #

Insightful piece, thanks a lot!

moving overseas | Reply



4/26/2010 11:32:49 AM #

You really know your stuff... Keep up the good work!

auction sites | Reply



4/26/2010 7:47:10 PM #

Whenever you see a successful business, someone once made a courageous decision.

faxless payday loans | Reply



4/27/2010 2:28:29 PM #

Intimately, the post is actually the best on this worthy topic. I harmonise with your conclusions and will eagerly look forward to your coming updates.

Hawaii Tattoo Parlor | Reply



4/27/2010 10:15:50 PM #

I\'m happy I found this blog, I couldnt discover any info on this subject matter prior to. I also run a site and if you want to ever serious in a little bit of guest writing for me if possible feel free to let me know, i\'m always look for people to check out my site. Please stop by and leave a comment sometime!

Rapidshare | Reply



4/29/2010 5:09:24 AM #

Hello this is my first post to this blog. I like the blog and I'm also having the knowledge of C# and the other s/w language like VB,PHp etc
I hope when i will visit the blog i will get the different info.
Thanks    

magic tricks | Reply



4/30/2010 6:36:24 AM #

Structure is nice method in C# where we can easy operate thanks

Cloth Diaper | Reply



4/30/2010 11:44:02 AM #

Work is not man's punishment. It is his reward and his strength and his pleasure.

payday loans | Reply



5/3/2010 10:19:14 AM #

Valuable information and excellent design you got here! I would like to thank you for sharing your thoughts and time into the stuff you post!!

book summaries | Reply



5/4/2010 12:20:20 PM #

I will keep visiting this blog very often.It is good to see you verbalise from the heart and your clarity on this important subject can be easily observed.

disaster recovery solutions | Reply



5/4/2010 3:09:52 PM #

What I liked about her, she didn't give you a lot of horse manure about what a great guy her father was.

Links of London Jewellery | Reply



5/5/2010 2:51:36 AM #

Its always good to learn tips like you share for blog posting. As I just started posting comments for blog and facing problem of lots of rejections. I think your suggestion would be helpful for me. I will let you know if its work for me too.
Thanks and keep post such a informative blogs.

simulateur de pret auto | Reply



5/6/2010 9:32:51 AM #

The magic word is: Union. Now you might say: Wait a second, C++ has unions, but C# does not have them and using pointers is also no fun in C#. Well, you still can use the StructLayout(LayoutKind.Explicit) attribute and then the FieldOffset(0) attribute to mark overlapping memory regions.

marin mountainbikes | Reply



5/6/2010 12:51:32 PM #

Thanks for the code...You are just too good...!!!

SEO Services India | Reply



5/8/2010 5:18:04 AM #

This is a nice blog.  Good clean UI and nice informative blog. I will be coming back soon, thanks for the great blog. I put a link to your blog at my site, hope you don't mind?

Watch Online Sports Free | Reply



5/15/2010 11:09:06 AM #

thank you for this interesting information I must post a link on my site so my readers can benefit from it as well. Great work thanks for sharing

SEO Services India | Reply



5/17/2010 9:28:15 AM #

To accomplish this I today present a very little cute trick on how to merge all those structs together and make them easily extensible: Yes, you can add methods to exsting structs without any helper classes!

seo company | Reply


Add comment




biuquote
  • Comment
  • Preview
Loading



Disclaimer: The opinions expressed in this blog are own personal opinions and do not represent the companies view.
© 2000-2011 exDream GmbH & MobileBits GmbH. All rights reserved. Legal/Impressum

Poll

Which platform should Soulcraft be released on next?











Show Results Poll Archive

Recent Games

Soulcraft

Fireburst

Jobs @ exDream

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910