簡體   English   中英

C#P / Invoke中的嵌套結構

[英]Nested structures in C# P/Invoke

我試圖調用具有以下結構的非托管DLL:

typedef struct
    {
      int num_objects;
      ppr_object_type *objects;
    } ppr_object_list_type;
ppr_coordinate_type;

typedef struct
{
  int model_id;
  ppr_coordinate_type position;
  float scale_factor;
  float size;
  ppr_rotation_type rotation;
  int nominal_width;
  int nominal_height;
  float confidence;
  int num_landmarks;
  ppr_landmark_type *landmarks;
} ppr_object_type;

typedef struct
{
  float x;
  float y;
} 

typedef struct
{
  float yaw;
  float pitch;
  float roll;
  ppr_precision_type precision;
} ppr_rotation_type;

這是我在C#端使用的:

[StructLayout(LayoutKind.Sequential)]
    public struct ObjectInfo
    {
        public int numObjects;
        public ObjectType objListPointer;
    }

[StructLayout(LayoutKind.Sequential)]
    public struct ObjectType
    {
        int model_id;
        Coordinate position;
        float scale_factor;
        float size;
        Rotation rotation;
        int nominal_width;
        int nominal_height;
        float confidence;
        int num_landmarks;
        IntPtr landmarks;

    }
    [StructLayout(LayoutKind.Sequential)]
    public struct Coordinate
    {
        float x;
        float y;
    }
    [StructLayout(LayoutKind.Sequential)]
    public struct Rotation
    {
        float yaw;
        float pitch;
        float roll;
        int precision;
    }

我正在撥打的電話是這樣指定的:

ppr_error_type ppr_detect_objects (ppr_context_type context,
                                   ppr_image_type image,
                                   ppr_object_list_type *object_list);

我的C#調用看起來像這樣:

ObjectInfo info = new ObjectInfo();
int objOK = ppr_detect_objects(context, imagePtr, ref info);

我知道ppr_object_list_type期望填充對象數組。 而且我知道C#會遇到嵌套對象的任意數組的麻煩。 我當時在想我做的方式只會返回第一個(這就是我所關心的)。

但是,當我這樣稱呼它時,“ num_objects”的值正確填充為1。model_id是錯誤的(看起來像一個內存地址),其他所有內容均為零。

任何幫助表示贊賞。 我已經做了很多工作,將結構傳遞給代碼管理,但是從來沒有做過這么復雜的事情。

ppr_object_list_type包含一個指向 ppr_object_type ,並非實際ppr_object_type值。

您需要將ObjectInfo更改為

[StructLayout(LayoutKind.Sequential)]
public struct ObjectInfo
{
    public int numObjects;
    public IntPtr objListPointer;
}

要訪問ObjectType值,您需要使用Marshal類中的方法。

如果您只關心第一個項目,這應該可以工作:

public struct ObjectInfo
{
    public int numObjects;
    [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)]
    public ObjectType[] objListPointer;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM