Use the fixed
statement:
fixed (double* aaPtr = aa) {
// You can use the pointer in here.
}
While in context of fixed
, the memory for your variable is pinned so the garbage collector will not try to move it around.
I would take this approach instead:
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);
}
}
}
}
This assumes of course CallFortranCode does not try to use the pointer outside of the call. Once the fixed statement goes out of scope the pointer is no longer valid...
UPDATE:
There is no way you can take the address of your argument double[] aa
and store it in your instance field. Even if the compiler would let you, the GC is bound to move that memory around leaving your pointer useless.
You could probably do this: Use Marshal.AllocHGlobal to allocate enough memory to store all the elements of the array (aa.Length * sizeof(double))
). Then, use Marshal.Copy to copy the contents of the array to your newly allocated memory:
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));
}
}
Hopefully this works...
Andrew