ctyp中结构数组的返回指针

2024-10-05 13:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个c++代码,看起来像这样,我想用ctypes从python调用它:

c++:

extern "C" Array<DetectionWindow>* getdets(const uint8_t *indatav, int rows, int cols){

/** Detection window struct */
typedef struct DetectionWindow
{
    ushort x;         /**< Top-left x coordinate */
    ushort y;         /**< Top-left y coordinate */
    ushort width;     /**< Width of the detection window */
    ushort height;    /**< Height of the detection window */
    ushort idx_class; /**< Index of the class */
    float  score;     /**< Confidence value for the detection window */
} DetectionWindow;

...
...

using DetectionWindowArray = Array<DetectionWindow>;

...

DetectionWindowArray win(100000);

Array<DetectionWindow>* dets = &win;

return dets ;
}

我不认为我在c++中做什么真的很重要。重要的是我返回一个指向结构数组的指针。通过编译源代码,我成功地创建了我想在python中使用的共享库。你知道吗

Python:

import numpy.ctypeslib as ctl
import ctypes
import numpy as np
import cv2
from numpy.ctypeslib import ndpointer

class detection(ctypes.Structure):
  _fields_ = [
                ('x', ctypes.c_ushort),
                ('y', ctypes.c_ushort),
                ('width', ctypes.c_ushort),
                ('height', ctypes.c_ushort),
                ('idx_class', ctypes.c_ushort),
                ('score', ctypes.c_float)
             ]

lib = ctypes.cdll.LoadLibrary("./lib/libmain.so")
getdets = lib.getdets

getdets.argtypes = [ctl.ndpointer(ctypes.c_uint8, flags='aligned, c_contiguous'), ctypes.c_int, ctypes.c_int]

img = cv2.imread('./data/image_0.jpg',0)

(???) = getdets(img , img.shape[0], img.shape[1])

如何通过在c++中返回的指针返回并打印数组中每个元素的所有结构参数?你知道吗


Tags: oftheimportnumpyimglibwindowctypes

热门问题