gpt4 book ai didi

c# - 从 double 组转换为指针

转载 作者:太空狗 更新时间:2023-10-29 21:15:34 29 4
gpt4 key购买 nike

我有这样的课

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);
}
}

如您所料,我需要将double 数组转换为指针。怎么做?

注意:互操作函数 Interop.CallFortranCode(double* dPtr) 是我无法更改的。

注2:两个构造函数都需要,因为我的API用户有的想传指针,有的想传数组。我不能强制他们选择。

最佳答案

使用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 不会尝试在调用之外使用指针。一旦 fixed 语句超出范围,指针就不再有效...

更新:

您无法获取参数 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));   }}

希望这能奏效...

安德鲁

关于c# - 从 double 组转换为指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2415017/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com