Link to home
Start Free TrialLog in
Avatar of rossryan
rossryan

asked on

IntPtr to byte[] array

How can I create a IntPtr to a byte[] array?
Avatar of AlexFM
AlexFM

I guess you want to pass managed byte array to unmanaged function (if I am wrong, correct me).
Create memory block of desired length using Marshal.AllocHGlobal Method:

IntPtr pUnmanaged = Marshal.AllocHGlobal(nArraySize);

Copy byte[] array to it using Marshal.Copy Method:

public static void Copy(
   byte[] source,
   int startIndex,
   IntPtr destination,
   int length
);

Marshal.Copy(byteArray, 0, pUnmanaged, nArraySize);

Now you can pass IntPtr pUnmanaged to unmanaged function. Don't forget to free pUnmanaged after this:

Marshal.FreeHGlobal(pUnmanaged);
Something like this will convert a bytes a C# structure...

byte[] sourceData;
MyStruct destStruct;
int arrayIndex = 0;

GCHandle handle = GCHandle.Alloc(sourceData, GCHandleType.Pinned);
try
{
IntPtr buffer = handle.AddrOfPinnedObject();
buffer = (IntPtr)(buffer.ToInt32() +
(arrayIndex*Marshal.SizeOf(typeof(MyStruct))));
destStruct = (MyStruct)Marshal.PtrToStructure(buffer, typeof(MyStruct));
}
finally
{
handle.Free();
}
If you need it for platform interop this is done by the compiler you can use the MarshalAsAttribute to specify the type of the marshalling. What do you want to use it for?
Avatar of rossryan

ASKER

I need to toss an IntPtr into a OpenGL sub, so that it can scale an image.

More precisely, I shove an IntPtr (from AlexFM) into the procedure, and does some scaling, and out pops another IntPtr.

Given that the original IntPtr pointed to a byte[] array, I think I need something comparable to receive the data.

Declaration of sub:

[C#]

[SuppressUnmanagedCodeSecurity]
public static int gluScaleImage(
   int format,
   int widthIn,
   int heightIn,
   int typeIn,
   IntPtr dataIn,
   int widthOut,
   int heightOut,
   int typeOut,
   IntPtr dataOut
);
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Description is lacking, but this is from the Tao C# libraries, so there are no C++ declaration used... :)