2

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?

Nick X Tsui
  • 2,737
  • 6
  • 39
  • 73
  • 1
    possible duplicate of [It is possible to get an IntPtr from an int\[\] array?](http://stackoverflow.com/questions/2238049/it-is-possible-to-get-an-intptr-from-an-int-array) – Tim S. Sep 23 '13 at 19:14
  • how do you like your double to be rounded to integer? – rajeemcariazo Sep 23 '13 at 19:24
  • 1
    @rajeem_cariazo: `IntPtr` is just a type in C# that allows you to store pointer in an integer. And, yes it also works on 64 bit. The IntPtr will receive the pointer to the memory, not the array values. –  Sep 23 '13 at 19:42

4 Answers4

4

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);
King King
  • 61,710
  • 16
  • 105
  • 130
1
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();
}
max
  • 33,369
  • 7
  • 73
  • 84
0

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.

0

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);
}
rajeemcariazo
  • 2,476
  • 5
  • 36
  • 62