【问题标题】:Get the value from unmanaged code to managed code从非托管代码中获取值到托管代码
【发布时间】:2016-06-06 06:50:53
【问题描述】:

我需要从C 非托管代码中获取值。实际上我从非托管调用函数,函数的返回类型是点,点是结构。

以下方式提到的结构

typedef struct point
{
    Poly* pol;
    NL_DEGREE p;
    VECTOR* vec;
} Point;

其中PolyVECTOR 是结构。

实际上我在C#中得到了IntPtr的返回值点。在得到IntPtr的值后,我尝试将这个Intptr转换为Array。以下面的方式转换Array

point[] Q = new point[2];
int size= Marshal.SizeOf(new point());
for (int i = 0; i < 2; i++)
{
    Q[i] = (point)Marshal.PtrToStructure(new IntPtr(Qptr.ToInt32() + (i * size)), typeof(point));
}

但是在得到数组后,每个结构元素的值都变成了null。我在这方面做错了什么,请任何人给我建议......

我在下面详细提到了用c#创建的结构。

public unsafe struct point
        {
            public Poly* pol;
            public NL_DEGREE p;
            public vECTOR* knt;
        }

哪里聚

public unsafe struct Poly
        { 
            public Int32 n;
            public cpoint* Pw;
        }

coint也是一个结构

public struct cpoint
        {
            public double x;
            public double y;
            public double z;
            public double w;
        }

向量在哪里

 public unsafe struct VECTOR
        {            
            public Int32 m;
            public double *U;          

        }

【问题讨论】:

    标签: c# unmanaged


    【解决方案1】:

    从您的代码 sn-p 中,尚不清楚 struct 在 C 中是如何定义的。假设某些默认对齐方式,您的 C# 定义应如下所示:

    public class Point
    {
      IntPtr pol;
      NL_DEGREE       p;
      IntPtr vec;
    }
    

    您仍然需要考虑具有适当 Pack 大小的精确结构布局(有关详细信息,请参阅 1

    所以在您的代码中,您必须执行以下操作:

    var point = (Point)Marshal.PtrToStructure(ptr, typeof(Point));
    var poly = (Poly)Marshal.PtrToStructure(point.pol, typeof(Poly));
    var vector = (Vector)Marshal.PtrToStructure(point.vec, typeof(Vector));
    

    由于 Poly 和 Vector 都可能是数组,您可能需要使用 IntPtr.Add() 2 方法来迭代这些数组。

    StructLayoutAttribute.Pack Field

    IntPtr.Add

    【讨论】:

    • 感谢您的回答,我已将用 c# 创建的结构的详细信息放在同一篇文章中
    猜你喜欢
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    相关资源
    最近更新 更多