Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8036527
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T02:38:58+00:00 2026-06-05T02:38:58+00:00

I need to convert the following struct to a byte array: [Serializable] public struct

  • 0

I need to convert the following struct to a byte array:

[Serializable]
public struct newLeads
{
    public string id;
    public string first_name;
    public string last_name;
}

I’m trying to convert to the byte array with the following code:

public class ConvertStruct
{
    public static byte[] StructureToByteArray(object obj)
    {
        int Length = Marshal.SizeOf(obj);
        byte[] bytearray = new byte[Length];
        IntPtr ptr = Marshal.AllocHGlobal(Length);
        Marshal.StructureToPtr(obj, ptr, false);
        Marshal.Copy(ptr, bytearray, 0, Length);
        Marshal.FreeHGlobal(ptr);
        return bytearray;
    }
}

I’m getting the exception on line:

IntPtr ptr = Marshal.AllocHGlobal(Length);

Exception: Attempt by security transparent method ‘Classes.ConvertStruct.ConvertStruct.StructureToByteArray(System.Object)’ to access security critical method ‘System.Runtime.InteropServices.Marshal.AllocHGlobal(Int32)’ failed.”}

My Question is? How can I fix this to avoid the exception and convert my simple struct into a byte[]?

Thanks in advance!

UPDATE: I tried this in a console application and it works. I’m calling this from an asp.net page code-behind so that must have something to do with it, but I can’t figure out what!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T02:39:00+00:00Added an answer on June 5, 2026 at 2:39 am
    1. Check the size of the struct, don’t box it.
    2. Set an appropiate marshaling for string (taking from the answer by goric), whithout that, what you will get is the memory address of the strings in the byte array (not a good thing).

      [Serializable]
      public struct newLeads
      {
          [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5000)]
          public string id;
          [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5000)]
          public string first_name;
          [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5000)]
          public string last_name;
      }
      
      [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
      public static byte[] ToByteArray(newLeads value)
      {
          int length = Marshal.SizeOf(typeof(newLeads));
          var result = new byte[length];
          IntPtr sourcePtr = Marshal.AllocHGlobal(length);
          Marshal.StructureToPtr(value, sourcePtr, false);
          Marshal.Copy(sourcePtr, result, 0, length);
          Marshal.FreeHGlobal(sourcePtr);
          return result;
      }
      

    In your comment you said that this code fails sooner. Well, it uses a Security Permission Demand (as recommended for .NET 4) at it will check for the particular permision each time the method is called. You may try to execute it without it, and the expected result is what you got at the begining.


    The real answer

    You must be running in a constrained enviroment, probably some kind of sandbox or a platform that doesn’t support pointers. In that case, we may need to do the convertion by other means.

    You said ASP.NET? so that’s it.

    In order to the convertion without pointers, try this technique:

    //You will have to decide an encoding.
    //If nto ASCII, try UTF8Encoding, UnicodeEncoding or (Hopefully not) UTF7Encoding
    void Main()
    {
        Encoding encoding = new ASCIIEncoding();
        newLeads target = GetNewLeads();
        byte[] id = EncodeString(target.id, encoding);
        byte[] first_name = EncodeString(target.first_name, encoding);
        byte[] last_name = EncodeString(target.last_name, encoding);
    }
    
    byte[] EncodeString(string str, Encoding encoding)
    {
        byte[] data;
        if (ReferenceEquals(str, null))
        {
            data = new byte[0];
        }
        else
        {
            data = encoding.GetBytes(str);
        }
        return data;
    }
    

    At this point I need to know a bit more about your situation to give you a better solution, in particular who or what is going to read that byte array?. Anyway, you could encode the length of the strings, like so (reserving -1 for null):

    byte[] EncodeString(string str, Encoding encoding)
    {
        byte[] data;
        byte[] data_length;
        Union union = new Union();
        if (ReferenceEquals(str, null))
        {
            data = new byte[0];
            union.data = -1;
        }
        else
        {
            data = encoding.GetBytes(str);
            union.data = str.Length;
        }
        data_length = new byte[]{union.a, union.b, union.c, union.c};
        int length = data.Length;
        byte[] result = new byte[4 + data.Length];
        System.Buffer.BlockCopy(data_length, 0, result, 0, 4);
        System.Buffer.BlockCopy(data, 0, result, 4, length);
        return result;
    }
    
    //I hope endianess doesn't bite
    [StructLayout(LayoutKind.Explicit)] 
    struct Union
    {
        [FieldOffset(0)]
        public int data;
        [FieldOffset(0)] 
        public byte a;
        [FieldOffset(1)] 
        public byte b;
        [FieldOffset(2)] 
        public byte c;
        [FieldOffset(3)] 
        public byte d;
    }
    

    Lastly, we need to join those arrays. I know this can be optimized much more… (A good idea for that use MemoryStream and StreamWriter) Anyway, this is my first implementation [tested]:

    byte[] ToByteArray(newLeads value)
    {
        Encoding encoding = new ASCIIEncoding(); //Choose some encoding
        byte[] id = EncodeString(value.id, encoding);
        byte[] first_name = EncodeString(value.first_name, encoding);
        byte[] last_name = EncodeString(value.last_name, encoding);
        byte[] result = new byte[id.Length + first_name.Length + last_name.Length];
        System.Buffer.BlockCopy(id, 0, result, 0, id.Length);
        System.Buffer.BlockCopy
            (
                first_name,
                0,
                result,
                id.Length,
                first_name.Length
            );
        System.Buffer.BlockCopy
            (
                last_name,
                0,
                result,
                id.Length + first_name.Length,
                last_name.Length
            );
        return result;
    }
    
    byte[] EncodeString(string str, Encoding encoding)
    {
        byte[] data;
        byte[] data_length;
        Union union = new Union();
        if (ReferenceEquals(str, null))
        {
            data = new byte[0];
            union.data = -1;
        }
        else
        {
            data = encoding.GetBytes(str);
            union.data = str.Length;
        }
        data_length = new byte[]{union.a, union.b, union.c, union.c};
        int length = data.Length;
        byte[] result = new byte[4 + data.Length];
        System.Buffer.BlockCopy(data_length, 0, result, 0, 4);
        System.Buffer.BlockCopy(data, 0, result, 4, length);
        return result;
    }
    
    //I hope endianess doesn't bite
    [StructLayout(LayoutKind.Explicit)] 
    struct Union
    {
        [FieldOffset(0)]
        public int data;
        [FieldOffset(0)] 
        public byte a;
        [FieldOffset(1)] 
        public byte b;
        [FieldOffset(2)] 
        public byte c;
        [FieldOffset(3)] 
        public byte d;
    }
    

    Note: I didn’t use null terminated strings because I don’t know what encoding you will end up using.

    Optimization

    Same logic, but implemented with streams (Union did not change)[tested].

    byte[] ToByteArray(newLeads value)
    {
        Encoding encoding = new ASCIIEncoding(); //Choose some encoding
        var stream = new MemoryStream();
        EncodeString(value.id, stream, encoding);
        EncodeString(value.first_name, stream, encoding);
        EncodeString(value.last_name, stream, encoding);
        int length = (int)stream.Length;
        byte[] result = new byte[(int)stream.Length];
        System.Buffer.BlockCopy(stream.GetBuffer(), 0, result, 0, length);
        stream.Close();
        return result;
    }
    
    void EncodeString(string str, Stream stream, Encoding encoding)
    {
        Union union = new Union();
        if (ReferenceEquals(str, null))
        {
            union.data = -1;
            stream.Write(new byte[]{union.a, union.b, union.c, union.c}, 0, 4);
        }
        else
        {
            union.data = str.Length;
            stream.Write(new byte[]{union.a, union.b, union.c, union.c}, 0, 4);
            var tmp = encoding.GetBytes(str);
            stream.Write(tmp, 0, tmp.Length);
        }
    }
    

    Reding the strings back

    To get the data back, we begin by reading the length of the string (With the same type Union):

    var newLeads = GetNewLeads();
    var z= ToByteArray(newLeads); //we have the byteArray in z
    
    var data = new MemoryStream(z); //Create an stream for convenience
    //Use the union to get the length
    var union = new Union()
        {
            a = (byte)data.ReadByte(),
            b = (byte)data.ReadByte(),
            c = (byte)data.ReadByte(),
            d = (byte)data.ReadByte()
        };
    Console.WriteLine(union.data); //the length of the first string
    

    Our next step would be to read that many characters, to do that we will use an StreamReader:

    var newLeads = GetNewLeads();
    var z = ToByteArray(newLeads);
    
    var data = new MemoryStream(z);
    var union = new Union()
        {
            a = (byte)data.ReadByte(),
            b = (byte)data.ReadByte(),
            c = (byte)data.ReadByte(),
            d = (byte)data.ReadByte()
        };
    var encoding = new ASCIIEncoding();
    string result = null;
    if (union.data != -1)
    {
        char[] finalChars = new char[union.data];
        var reader = new StreamReader(data, encoding);
        reader.Read(finalChars, 0, union.data);
        result = new string(finalChars);
    }
    Console.WriteLine(result);
    

    With this we build a method to decode the strings:

    string DecodeString(Stream data, Encoding encoding)
    {   
        //TODO: You may want to validate that data and encoding are not null
        //or make this private
        var union = new Union()
        {
            a = (byte)data.ReadByte(),
            b = (byte)data.ReadByte(),
            c = (byte)data.ReadByte(),
            d = (byte)data.ReadByte()
        };
        string result = null;
        if (union.data != -1)
        {
            char[] finalChars = new char[union.data];
            var reader = new StreamReader(data, encoding);
            reader.Read(finalChars, 0, union.data);
            result = new string(finalChars);
        }
        return result;
    }
    
    //Convenience method, not needed:
    
    string DecodeString(byte[] data, Encoding encoding)
    {
        //TODO: You may want to validate that data and encoding are not null
        //or make this private
        return DecodeString(new MemoryStream(data), encoding);
    }
    

    And finally the method to recover a newLeads (Again with the same Union type)[tested]:

    newLeads FromByteArray(byte[] data)
    {
        //TODO: Validate that data is not null
        Encoding encoding = new ASCIIEncoding(); //Choose the same encoding
        newLeads result = new newLeads();
        var reader = new StreamReader(new MemoryStream(data), encoding);
        result.id = DecodeString(reader);
        result.first_name = DecodeString(reader);
        result.last_name = DecodeString(reader);
        reader.Close();
        return result;
    }
    
    
    //Changed to reuse StreamReader...
    //Because closing it will close the underlying stream
    string DecodeString(StreamReader reader)
    {
        //TODO: You may want to validate that reader is not null
        //or make this private
        var data = reader.BaseStream;
        var union = new Union()
        {
            a = (byte)data.ReadByte(),
            b = (byte)data.ReadByte(),
            c = (byte)data.ReadByte(),
            d = (byte)data.ReadByte()
        };
        string result = null;
        if (union.data != -1)
        {
            char[] finalChars = new char[union.data];
            reader.Read(finalChars, 0, union.data);
            result = new string(finalChars);
        }
        return result;
    }
    
    //Convenience method, not needed:
    
    string DecodeString(byte[] data, Encoding encoding)
    {
        //TODO: You may want to validate that data and encoding are not null
        //or make this private
        return DecodeString(new StreamReader(new MemoryStream(data), encoding));
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How can I convert following code to VB.NET? class A { public int NumberA
I need to convert the following string to the amount of seconds I tried
I have the following FORTRAN code which I need to convert to C or
I am creating an array as below: public struct Smb_Parameters { public byte WordCount;
The following is some old ASMX code which I need to convert to WCF
I will need to convert the following VB Form code to WPF C# :
I need to convert this following XAML into code-behind: <ComboBox SelectedItem={Binding Level} ItemsSource={Binding Levels}
I have the following problem: i need to convert a decimal number to string.
I need help from some one to convert the following line of code from
I have the following code using normal Zend routing and I need to convert

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.