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 9217173
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T02:34:58+00:00 2026-06-18T02:34:58+00:00

I am having a problem with marshalling a C character array. I have the

  • 0

I am having a problem with marshalling a C character array. I have the following C# structure:

[StructLayout(LayoutKind.Explicit, Size = 16, CharSet = CharSet.Ansi), Serializable]
internal struct Header
{
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 4)]
    [FieldOffset(0)]
    public string header;

    [FieldOffset(4)]
    public int version;

    [FieldOffset(8)]
    public int diroffset;

    [FieldOffset(12)]
    public int direntries;
}

and the following code to read this structure from a stream:

public static T ReadStruct<T>(this Stream stream) where T : struct
{
    var sz = Marshal.SizeOf(typeof(T));
    var buffer = new byte[sz];
    stream.Read(buffer, 0, sz);

    var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);

    var structure = (T) Marshal.PtrToStructure(
        pinnedBuffer.AddrOfPinnedObject(), typeof(T));

    pinnedBuffer.Free();
    return structure;
}

Now my problem is that the header field misses a character after the struct is read. The file where the struct is read from contains the four bytes VPVP but after the struct has been read by ReadStruct the header string only contains VPV. If I take a look at the byte array in the read function in the debugger then that array contains the values 86, 80, 86, 80 which is VPVP. I also tried using LayoutKind.Sequential for the StructLayout but that didn’t change anything.

Am I doing something wrong or why is there a character missing in my string?

  • 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-18T02:34:59+00:00Added an answer on June 18, 2026 at 2:34 am

    The problem you’re having lies in the struct definition, not in writing the bytes to it.

    The problem lies right here:

    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 4)]
    

    As you’ve stated, you’re writing out the text VPVP, which is 4 characters long, you’d think. This, however, is not the case. In C, you could declare the string as such:

    char mystring[] = { 'V', 'P', 'V', 'P', '\0' };
    

    You need that null character (\0) at the end, to mark off the end of the string. You need to take this into account when marshalling, because you need to reserve space for that “null terminator byte”, if you do not, the C# string will add it for you in the available memory, so it will eat away your last character. So if you’re gonna use a null-terminated string, you will have to make it of length 5.


    EDIT: Here is a better solution, where you don’t have to worry about null-terminators, you just use a char[] (and you also keep the magic 16 byte size):

    [StructLayout(LayoutKind.Explicit, Size = 16, CharSet = CharSet.Ansi), Serializable]
    internal struct Header
    {
        [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4)]
        [FieldOffset(0)]
        private char[] headerCharArray;
    
        public string header
        {
            get { return new string(headerCharArray); }
            set
            {
                if (value.Length == 4)
                {
                    headerCharArray = value.ToArray();
                }
                else
                {
                    throw new InvalidOperationException("String length was not 4.");
                }
            }
        }
    
        [FieldOffset(4)]
        public int version;
    
        [FieldOffset(8)]
        public int diroffset;
    
        [FieldOffset(12)]
        public int direntries;
    }
    

    That way the char[] is stored in memory, and you can access it as a string through the property, which doesn’t take in any memory of the struct itself.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

m having problem in passing parameter to controller action, i have done the following
Im having problem in my UIscrollView ,this is what I have done: Whenever a
I'm having problem with datagrid view. I have attached an image with the code
hello I am having problem related to https:// . I have used FB.getLoginStatus(function(response) function
I'am having problem in accessing json array elements. Below is the response when i
im having problem whith a POST request. I have to receive an XML message
hey there i am having problem i have List<List<memoryCard>> that i want to show
I am having problem in django. I have created a form in my app
I am having a problem with Marshalling an object across application domains in a
Im having problem with cordova xcode app. I already have my html page setup.

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.