473,573 Members | 5,083 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C#-App marshal very complex structures.

3 New Member

I hate having to do this, because im almost certain there is someone in the world that has come across this problem and i just havent found their solution yet, so i do appologise if this has already been covered.

I have been trying to learn c# as fast as possible in the last month and in doing so i have been re-visiting old C/C++ problems and trying to overcome them in C#.

What i have is a very complex serise of structures. Id rather not change them, as it would cause a lot of work through the rest of the app, however they are causing me problems when it comes to saving the data they contain. My app passes the content of the structures through an encryption algorithem as a byte array, and so here is where the problem starts.

My structures are nested as many as five-deep, all containing strings, string arrays and arrays of other structures (did i mention its a nightmare?)

I have made some head-way with this, and can quite successfully convert a structure to a byte array using the following code-

Expand|Select|Wrap|Line Numbers
  1. static byte [] StructureToByteArray(object obj)
  2. {
  3.     int len = Marshal.SizeOf(obj);
  4.     byte [] arr = new byte[len];
  5.     IntPtr ptr = Marshal.AllocHGlobal(len);
  6.     Marshal.StructureToPtr(obj, ptr, true);
  7.     Marshal.Copy(ptr, arr, 0, len);
  8.     Marshal.FreeHGlobal(ptr);
  9.     return arr;
  10. }
I have tried many changes to this code, but i always seem to get an error when handling more than one nested structure (I.E struct A contains struct B and struct C) or structures nested more than 1 deep (I.E struct A contains struct B which contains struct C).

The errors i am getting are as follows:-

"Object reference not set to an instance of an object"

- when working with deep nested structures,or the following error :-

"Type ssc.app.structD ata can not be marshaled as an unmanaged structure; no meaningful size or offset can be computed."

- when working with several structures nested in the same structure

Any solutions to my problem would be of great help (including telling me to rip it all out and start again =))

Kind regards,
Nov 16 '07 #1
4 4705
7,872 Recognized Expert Expert
My advice: Avoid using Structs if you can. Use Classes instead, they're slightly easit to work with.

I've never had to use the Marshalling stuff ( I avoiding using Serializing in Java and by golly I'll avoid Marshalling in .NET) But it rather seems like sizeof() would not work for struct with another struct in it, unless the nested structure already had a definitive size determined for it?

I like classes because I can have a constructor like:
Expand|Select|Wrap|Line Numbers
  1. public myclass(byte[] DataBytes)
  2. {
  3. //...
  4. }
And a function like:
Expand|Select|Wrap|Line Numbers
  1. public byte[] GetDataBytes()
  2. {
  3. //...
  4. }
Nov 19 '07 #2
3 New Member
Thank you for the reply.

I had a feeling you would tell me to switch to classes. Thankfully that shouldn’t be "too" much work, however I’m still a little confused with how you think I should be able to convert these classes into a byte array. One of the biggest problems is that I do not know the contents of any of my data until the moment I want to encrypt this and save it, and I am trying to minimize the usage of encrypt while keeping things straight forward enough to decrypt my data later on. encrypt/decrypt naturally take a lot of time to complete, so I would rather have one large byte array which I can feed through the encrypter in one go, than several calls with much less data.
To this extent, I feel I would either have to update a byte array in each class which contains the classes data and gather this when I want to encrypt it all, or I would have to traverse through each class getting to the deepest nested class, and work backwards through all my classes, generating the byte array as I go until I have all my data in one byte array ready to be passed to the encrypter (and in both cases make sure I know the order the data is stored in the array, so I know how to pull it apart when exiting the decrypter after a load!)

I originally went for structures, as I knew I could convert a structure to a byte array quite easily, however I seem to have quickly lost myself in the scale of this application. Naturally, I can foresee problems arising again later where my array of structures (which each contain a couple of structures within them each of them) need converting. Oh joy.

I’m starting to feel that my data structures are over complicated and could really be re-done in a better way. I would really appreciate any ideas on how to overcome these problems.
Nov 20 '07 #3
7,872 Recognized Expert Expert
Well as far as byte[]->class and back:
Expand|Select|Wrap|Line Numbers
  1. public class DispValueType
  2. {
  3.    public Int32 stat = 0;
  4.    public float[] vals = new float[18];
  5.    public byte[] theData= new byte[0];
  7.    public DispValueType(byte[] mybuff)
  8.    {
  9.       if (mybuff.Length != (4 + (vals.Length * 4)))
  10.       {
  11.          return;//not enough data
  12.       }
  13.       theData = mybuff;
  14.       stat = MyConversions.MakeInt32(mybuff, 0);
  15.       for (int i = 0; i < vals.Length; i++)
  16.       {
  17.          vals[i] = MyConversions.MakeFloat(mybuff, 4 + (i * 4));
  18.       }
  19.    }
  20. }//end of class 
As for the rest of, not sure I really know much about what you're doing, I just didn't want to leave you hanging without a response.
Nov 20 '07 #4
3 New Member
Thanks for getting back to me.
I will look into that code and see what i can do with it.
Nov 20 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Ivan | last post by:
Hi All, I have a problem with marshaling complex structures (containing numbers, strings, arrays of another structures) to native C function in dll. I have already posted same question to .compactframework thread, but nobody helped. main problem is that I have tried all the workarounds I have found in the Inet but nothing worked... I...
by: Andre | last post by:
Hi, I have a problem with marshaling nested structures struct a { struct b s_b; struct d s_d;
by: Brusex via DotNetMonster.com | last post by:
Hi I am trying to make to work this unmanaged Function from C to VB.Net My GetCarList Function returns always 0 (ERROR_NONE=0) but the structures are all empty. Can someone help me to resolve this problem, even with an example? Regards
by: Ivan | last post by:
Hi All, I have a problem with marshaling complex structures (containing numbers, strings, arrays of another structures) to native C function in dll. I have already posted same question to .compactframework thread, but nobody helped. main problem is that I have tried all the workarounds I have found in the Inet but nothing worked... I...
by: Mike | last post by:
Hi, The example below shows that result of a marshaled data structure is nothing but a string >>> data = {2:'two', 3:'three'} >>> import marshal >>> bytes = marshal.dumps(data) >>> type(bytes) <type 'str'>
by: --Fragman-- | last post by:
Hello all, I'm creating some kind of object oriented drawing program, my classes consist of points, lines, quads, etc... Right now I'm implementing undo/redo and copy/paste functionality. For that I need to create deep copies of my objects, but set some property fields to null in some cases. For example I have an attachment feature which...
by: gpg | last post by:
I am using a legacy DLL and need to marshal some structures for use in the DLL. For the most part, I have figured out my needs except for one small item. I have a structure that contain, among other items, an array of bools (not BOOL). The array is a fixed size and is contained in the structure. Should be simple ie:
by: efrat | last post by:
Hello, I'm planning to use Python in order to teach a DSA (data structures and algorithms) course in an academic institute. If you could help out with the following questions, I'd sure appreciate it: 1. What exactly is a Python list? If one writes a, then is the complexity Theta(n)? If this is O(1), then why was the name "list" chosen? If...
by: oleop | last post by:
I am trying to call dll from the managed code.eveyrting works OK until i'm trying to use fucntions that use complex (containing arrays of structures) structures as a parameters. Let's say private static extern int myFunc(ref STRUCT2 someStrust);
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.