using System.Runtime.InteropServices;
/* ... */
double[] rotX = { 1.0, 0.0, 0.0 };
double[] rotY = { 0.0, 1.0, 0.0 };
double[] rotZ = { 0.0, 0.0, 1.0 };
var gchX = default(GCHandle);
var gchY = default(GCHandle);
var gchZ = default(GCHandle);
try
{
gchX = GCHandle.Alloc(rotX, GCHandleType.Pinned);
gchY = GCHandle.Alloc(rotY, GCHandleType.Pinned);
gchZ = GCHandle.Alloc(rotZ, GCHandleType.Pinned);
SetRotationDirection(
gchX.AddrOfPinnedObject(),
gchY.AddrOfPinnedObject(),
gchZ.AddrOfPinnedObject());
}
finally
{
if(gchX.IsAllocated) gchX.Free();
if(gchY.IsAllocated) gchY.Free();
if(gchZ.IsAllocated) gchZ.Free();
}
Marshall double[] to IntPtr in C#?
-
29-06-2022 - |
Question
I am trying to convert double[] to IntPtr in C#. Here is the data I am going to convert:
double[] rotX = { 1.0, 0.0, 0.0 };
double[] rotY = { 0.0, 1.0, 0.0 };
double[] rotZ = { 0.0, 0.0, 1.0 };
Here is the function I am going to feed in the IntPtr, which is converted from the array above:
SetRotationDirection(IntPtr rotX, IntPtr rotY, IntPtr rotZ);
How should I do the job?
Solution 2
OTHER TIPS
You can try using Marshal.AllocCoTaskMem
and Marshal.Copy
:
double[] d = new double[] {1,2,3,4,5 };
IntPtr p = Marshal.AllocCoTaskMem(sizeof(double)*d.Length);
Marshal.Copy(d, 0, p, d.Length);
IntPtr represent a platform specific integer. It's size is either 4 or 8 bytes depending on the target platform bitness.
How would you like to convert a double to an integer? you should expect data truncation.
You can do something like this:
for(int i = 0; i < 3; i++) {
var a = new IntPtr(Convert.ToInt32(rotX[i]));
var b = new IntPtr(Convert.ToInt32(rotY[i]));
var c = new IntPtr(Convert.ToInt32(rotZ[i]));
SetRotationDirection(a, b, c);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow