5

how can i define a struct with a dynamic sized array?

is it right?

struct MyStruc { 

    public int len; 
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)]
    public int buf[]; 
}
6
  • What is 'dynamic sized array'? Array like List<int>? Commented Apr 2, 2014 at 12:40
  • You will have to make it an IntPtr or go unsafe (the latter might be easier to get things working correctly). Commented Apr 2, 2014 at 12:41
  • i cant use List because in c++ size definition like int* Commented Apr 2, 2014 at 12:45
  • It is not dynamically sized, it only ever takes 8 bytes in 32-bit mode. Surely you meant UnmanagedType.ByValArray? It is a common trick in C code. Commented Apr 2, 2014 at 12:48
  • 3
    No, ByValArray is for inline arrays whose size is known at compile time. Commented Apr 2, 2014 at 12:56

1 Answer 1

5

Assuming that you want a struct containing a pointer to the array.

Declare the pointer to the array as IntPtr and marshal the array contents manually with Marshal.AllocHGlobal, Marshal.Copy etc.

Assuming that you want a variable sized struct rather than a struct containing a pointer to the array.

You cannot marshal a variable sized struct using p/invoke. You have at least these two options:

  1. Break the struct into two parameters.
  2. Marshal the struct manually with Marshal.AllocHGlobal, Marshal.Copy etc.
Sign up to request clarification or add additional context in comments.

11 Comments

Ok i understand but i don't want to work with IntPtr in c# :( but i guess, i haven't got an other way.
Which of my two assumptions is correct. Showing the C++ declaration of the type would have helped.
Actually, i'm using a dll and i haven't got dll codes. But i have got dlls' definition of struct. the definition like this: struct MyStruc { int len; int buf[1]; }
But when i talked with developer who is developed this dll, he said to me this buf hasn't got fixed size, it can be dynamicaly.
I guess, dll side is using pointer to buff and return an array.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.