使用C++中的CPPYY读取用户定义的结构中的CHAR16*T*字符串

2024-10-01 07:40:12 发布

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

根据这个问题:Read char16_t* String with cppyy from c++ 我对用户定义结构中的char16_t*有一个新问题

给出C++函数:

MLPI_API MLPIRESULT mlpiMotionGetConfiguredAxes(const MLPIHANDLE connection, MlpiAxisInformation* configAxes, const ULONG numElements, ULONG *numElementsRet);

typedef unsigned int                  ULONG;
typedef char16_t                    WCHAR16;
typedef struct MlpiAxisInformation
{
  MlpiAxisRef     axis;                                 //!< Logical axis address.
  ULONG           deviceAddress;                        //!< (SERCOS) device address.
  MlpiAxisType    axisType;                             //!< Type of axis (virtual, real, etc...).
  WCHAR16         name[MLPI_MOTION_MAX_AXIS_NAME_LEN];  //!< The axis name.
}MlpiAxisInformation;

对于ctypes,我将结构定义为类,并从中构建了一个数组。但是字符串不起作用。Cppyy能够处理刺痛,但我不知道如何交出数组并包装字符串

(工作)香草C类型代码:

class MlpiAxisRef(ctypes.Structure):
    _fields_ = [
        ("controlNo",ctypes.c_int),
        ("axisNo",ctypes.c_int)]


class MlpiAxisInformation(ctypes.Structure):
    _fields_ = [
        ("axis", MlpiAxisRef),
        ("deviceAddress",ctypes.c_ulong),
        ("axisType", ctypes.c_int),
        ("name", ctypes.c_wchar*100)
        ]

def MLPIGetConfiguredAxes(self) -> List[MlpiAxisInformation]:
        length = ctypes.c_ulong(99)
        length_ret = ctypes.c_ulong(0)

        self._mlpi.mlpiMotionGetConfiguredAxes.argtypes = (ctypes.c_ulonglong, ctypes.POINTER(MlpiAxisInformation), ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong))
        self._mlpi.mlpiMotionGetConfiguredAxes.restype = ctypes.c_long
        val = (MlpiAxisInformation*100)()
        ret = self._mlpi.mlpiMotionGetConfiguredAxes(self.con, val, length, length_ret)

如何使用工作字符串返回MlpiAxisInformation数组

cppyy=“==1.7.0”,因为dockerize更高版本中存在问题


Tags: 字符串nameself数组ctypeslengthintaxis
1条回答
网友
1楼 · 发布于 2024-10-01 07:40:12

虽然我仍然不清楚这里的实际意图,特别是因为没有可运行的示例,但我猜其要点是数组类型被视为“数据”而不是“字符串”,您希望这种解释被颠倒

让我们从一些可运行的东西开始:

import cppyy

cppyy.cppdef(r"""\
  struct AxisInformation {
  AxisInformation() : name{u'h', u'e', u'l', u'l', u'o', u'\0'} {}
  char16_t name[16];
};""")

ai = cppyy.gbl.AxisInformation()

此时,ai.name是一种数组类型,因此,例如print(ai.name)将产生<cppyy.LowLevelView object at 0x7fe1eb0b31b0>。现在,要将char16_t[]视为字符串,它应该是char16_t。到达那里的一个方法是施展:

import cppyy.ll
name = cppyy.ll.cast['char16_t*'](ai.name)

打印时,现在生成hello

这就是你想要的吗

注意,有一个公开的bug报告,有一个建议的解决方案,注释这些字符数组应该代表什么,因为它是C++的一个普遍问题,即“数据”通常表示为一些易于使用指针算法的字符类型。(因此,自动转换必须猜测最可能的用法;这里是错误的):https://bitbucket.org/wlav/cppyy/issues/344/failed-to-handle-char-array-with-arbitrary

相关问题 更多 >