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?

3
  • 1
    possible duplicate of It is possible to get an IntPtr from an int[] array?
    – Tim S.
    Sep 23, 2013 at 19:14
  • how do you like your double to be rounded to integer? Sep 23, 2013 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.
    – user180326
    Sep 23, 2013 at 19:42

4 Answers 4

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);
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();
}
0
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.

1
  • The op wants to convert a pointer to a double to a 64 bit integer. That should work without truncation. Jan 5, 2021 at 7:21
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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.