Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use the <code>fixed</code> statement:</p> <pre> fixed (double* aaPtr = aa) { // You can use the pointer in here. } </pre> <p>While in context of <code>fixed</code>, the memory for your variable is pinned so the garbage collector will not try to move it around.</p> <p>I would take this approach instead:</p> <pre> 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); } } } } </pre> <p>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...</p> <p>UPDATE:</p> <p>There is no way you can take the address of your argument <code>double[] aa</code> 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. </p> <p>You could probably do this: Use Marshal.AllocHGlobal to allocate enough memory to store all the elements of the array (<code>aa.Length * sizeof(double))</code>). Then, use Marshal.Copy to copy the contents of the array to your newly allocated memory:</p> <pre> 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)); } } </pre> <p>Hopefully this works...</p> <p>Andrew</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload