rossryan
asked on
IntPtr to byte[] array
How can I create a IntPtr to a byte[] array?
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(My Struct)))) ;
destStruct = (MyStruct)Marshal.PtrToStr ucture(buf fer, typeof(MyStruct));
}
finally
{
handle.Free();
}
byte[] sourceData;
MyStruct destStruct;
int arrayIndex = 0;
GCHandle handle = GCHandle.Alloc(sourceData,
try
{
IntPtr buffer = handle.AddrOfPinnedObject(
buffer = (IntPtr)(buffer.ToInt32() +
(arrayIndex*Marshal.SizeOf
destStruct = (MyStruct)Marshal.PtrToStr
}
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?
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#]
[SuppressUnmanagedCodeSecu rity]
public static int gluScaleImage(
int format,
int widthIn,
int heightIn,
int typeIn,
IntPtr dataIn,
int widthOut,
int heightOut,
int typeOut,
IntPtr dataOut
);
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#]
[SuppressUnmanagedCodeSecu
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Description is lacking, but this is from the Tao C# libraries, so there are no C++ declaration used... :)
Create memory block of desired length using Marshal.AllocHGlobal Method:
IntPtr pUnmanaged = Marshal.AllocHGlobal(nArra
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(pUnman