Convert from double array to pointer

I have such a class

public unsafe class EigenSolver
{
   public double* aPtr
   {get; private set;}
   public EigenSolver(double* ap)
   {
      aPtr = ap;
   }
   public EigenSolver(double[] aa)
   {
     // how to convert from aa double array to pointer?
   }

   public void Solve()
   {
     Interop.CallFortranCode(aPtr);
   }
}

As you can guess, I need to convert from an array doubleto a pointer. How to do it?

Note: the interop function Interop.CallFortranCode(double* dPtr)is something that I cannot change.

Note 2: Both constructors are necessary because some of my API users want to pass pointers, and some would like to pass an array. I can not get them to choose.

+5
source share
2 answers

Use the operator fixed:

fixed (double * aaPtr = aa) {
   // You can use the pointer in here.
}

fixed , .

:

public class EigenSolver
{
   public double[] _aa;
   /*
   There really is no reason to allow callers to pass a pointer here, 
   just make them pass the array.
   public EigenSolver(double* ap)
   {
      aPtr = ap;
   }
   */
   public EigenSolver(double[] aa)
   {
     _aa = aa;
   }

   public void Solve()
   {
     unsafe {
        fixed (double* ptr = _aa) {
           Interop.CallFortranCode(ptr);
        }
     }
   }
}

, , , CallFortranCode . , ...

UPDATE:

double[] aa . , GC , .

, : Marshal.AllocHGlobal (aa.Length * sizeof(double))). Marshal.Copy :

bool _ownsPointer; 
public EigenSolver(double[] aa) {
   IntPtr arrayStore = (double*)Marshal.AllocHGlobal(aa.Length * sizeof(double));
   Marshal.Copy(aa, 0, arrayStore, aa.Length);
   this.aPtr = (double*)arrayStore.ToPointer();
   _ownsPointer = true;
}

~EigenSolver {
   if (_ownsPointer) {
      Marshal.FreeHGlobal(new IntPtr(this.aPtr));
   }
}

, ...

+8

fixed , , , . fixed ( ), . . , .

( ) Solve. , , interrop- fortran, gc .

+1

All Articles