Search code examples
c#memory-managementintpinvokeref

Is it possible to create a 6400 byte integer?


I have a function which I can't alter because of protection and abstraction, and it is declared like this:

GetDeviceLongInfo(int, int, ref int);

In which the "ref int" argument to be passed is said to give back 6400 bytes of information.

My question is, how can I get this information in a variable if the only choice I have is to give the function an Int32? Can I allocate more memory for that Int32? Is this even possible to achieve in some way?

EDIT: I can tell you that the function uses the ref int to dump values in it, the int size (size of the information) is not fixed, depends on the option chosed in the second parameter. I can't even look at the function to see how it uses that ref.


Solution

  • You can allocate an int[] and pass that to the function. This is a hack but I don't see why it should not be safe.

    var array = new int[6400 / sizeof(int)];
    GetDevice(..., ref array[0]);
    

    The array is pinned by the CLR for the duration of the call.

    Note, that ref is a so called managed pointer to the CLR. It is marshaled by passing it as a pointer and pinning the object it points to. An int[] would be passed in almost the same way (a pointer to the first element is passed).