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

  • Home
  • SEARCH
  • 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 332421
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T09:51:55+00:00 2026-05-12T09:51:55+00:00

I tried to allocate an array of structs in this way: struct T {

  • 0

I tried to allocate an array of structs in this way:

struct T {
    int a; int b;
}

data = Marshal.AllocHGlobal(count*Marshal.SizeOf(typeof(T));
...

I’d like to access to allocated data “binding” a struct to each element in array allocated
with AllocHGlobal… something like this

T v;
v = (T)Marshal.PtrToStructure(data+1, typeof(T));

but i don’t find any convenient way… why IntPtr lack of arithmetics? How can I workaround this in a “safe” way?

Someone could confirm that PtrToStructure function copy data into the struct variable? In other words, modifing the struct reflect modifications in the structure array data, or not?

Definitely, I want to operate on data pointed by an IntPtr using struct, without copying data each time, avoiding unsafe code.

Thank all!

  • 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-05-12T09:51:55+00:00Added an answer on May 12, 2026 at 9:51 am

    You have four options that I can think of, two using only “safe” code, and two using unsafe code. The unsafe options are likely to be significantly faster.

    Safe:

    • Allocate your array in managed memory, and declare your P/Invoke function to take the array. i.e., instead of:

      [DllImport(...)]
      static extern bool Foo(int count, IntPtr arrayPtr);
      

      make it

      [DllImport(...)]
      static extern bool Foo(int count, NativeType[] array);
      

      (I’ve used NativeType for your struct name instead of T, since T is often used in a generic context.)

      The problem with this approach is that, as I understand it, the NativeType[] array will be marshaled twice for every call to Foo. It will be copied from managed memory to unmanaged
      memory before the call, and copied from unmanaged memory to managed memory afterward. It can be improved, though, if Foo will only read from or write to the array. In this case, decorate the tarray parameter with an [In] (read only) or [Out] (write only) attribute. This allows the runtime to skip one of the copying steps.

    • As you’re doing now, allocate the array in unmanaged memory, and use a bunch of calls to Marshal.PtrToStructure and Marshal.StructureToPtr. This will likely perform even worse than the first option, as you still need to copy elements of the array back and forth, and you’re doing it in steps, so you have more overhead. On the other hand, if you have many elements in the array, but you only access a small number of them in between calls to Foo, then this may perform better. You might want a couple of little helper functions, like so:

      static T ReadFromArray<T>(IntPtr arrayPtr, int index){
          // below, if you **know** you'll be on a 32-bit platform,
          // you can change ToInt64() to ToInt32().
          return (T)Marshal.PtrToStructure((IntPtr)(arrayPtr.ToInt64() +
              index * Marshal.SizeOf(typeof(T)));
      }
      // you might change `T value` below to `ref T value` to avoid one more copy
      static void WriteToArray<T>(IntPtr arrayPtr, int index, T value){
          // below, if you **know** you'll be on a 32-bit platform,
          // you can change ToInt64() to ToInt32().
          Marshal.StructureToPtr(value, (IntPtr)(arrayPtr.ToInt64() +
              index * Marshal.SizeOf(typeof(T)), false);
      }
      

    Unsafe:

    • Allocate your array in unmanaged memory, and use pointers to access the elements. This means that all the code that uses the array must be within an unsafe block.

      IntPtr arrayPtr = Marhsal.AllocHGlobal(count * sizeof(typeof(NativeType)));
      unsafe{
          NativeType* ptr = (NativeType*)arrayPtr.ToPointer();
      
          ptr[0].Member1 = foo;
          ptr[1].Member2 = bar;
          /* and so on */
      }
      Foo(count, arrayPtr);
      
    • Allocate your array in managed memory, and pin it when you need to call the native routine:

      NativeType[] array = new NativeType[count];
      array[0].Member1 = foo;
      array[1].Member2 = bar;
      /* and so on */
      
      unsafe{
          fixed(NativeType* ptr = array)
              Foo(count, (IntPtr)ptr);
              // or just Foo(count, ptr), if Foo is declare as such:
              //     static unsafe bool Foo(int count, NativeType* arrayPtr);
      }
      

    This last option is probably the cleanest if you can use unsafe code and are concerned about performance, because your only unsafe code is where you call the native routine. If performance isn’t an issue (perhaps if the size of the array is relatively small), or if you can’t use unsafe code (perhaps you don’t have full trust), then the first option is likely cleanest, although, as I mentioned, if the number of elements you’ll access in between calls to the native routine are a small percentage of the number of elements within the array, then the second option is faster.

    Note:

    The unsafe operations assume that your struct is blittable. If not, then the safe routines are your only option.

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

Sidebar

Related Questions

No related questions found

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.