【问题标题】:How to dereference member from struct in which the definition is hid from user?如何从对用户隐藏定义的结构中取消引用成员?
【发布时间】:2019-06-10 10:43:37
【问题描述】:

Payload_Manager.h

typedef struct ATEIS_Payload_s* pATEIS_Payload;

Payload_Manager.c

#include "Payload_Manager.h"

struct __attribute__((__packed__))ATEIS_Payload_s   //payload
{
    uint32_t Addr;
    uint16_t Cmd;
    uint16_t Len;
    uint8_t Data[]; 
};

DNM_Manager.h

#include "Payload_Manager.h"

typedef struct DNM_s* pDNM;

pDNM DNMManager_Ctor(pDNM this, pATEIS_Payload src);

DNM_Manager.c

#include "Payload_Manager.h"

struct DNM_s
{
    uint32_t Addr;
    uint32_t SerialNo;
    uint32_t SubnetMask;
    uint16_t Tick;
    uint8_t Name[NAME_SIZE];
}DNMSet[SET_SIZE], DNMTemp;

pDNM DNMManager_Ctor(pDNM this, pATEIS_Payload src)
{
    memcpy(this->Name, &src->Data[NAME], NAME_SIZE);    //ptr to incomplete class type is not allowed
    this->Addr = src->Addr;    //ditto
    this->SerialNo = *(uint32_t*)&src->Data[SN];    //ditto
    this->SubnetMask = *(uint32_t*)&src->Data[SUBMASK];    //ditto
    this->Tick = 0;
    return this;
}

main.c

#include "Payload_Manager.h"
#include "DNM_Manager.h"

pDNM DNM_temp = NULL;
DNM_temp = DNMManager_New();    //get one DNM
DNM_temp = DNMManager_Ctor(DNM_temp, pl_p);    //init DNM_temp by pl_p

文件DNM_Manager.c需要知道ATEIS_Payload_s的声明,否则无法解引用。

除了在 DNM_Manager.c 中再次声明 ATEIS_Payload_s,我还能做什么?

谢谢。

【问题讨论】:

  • 将结构定义移动到Payload_Manager.h
  • 或者定义一个函数从Payload_Manager.c中的struct中获取指向名字的指针
  • 由于您正在访问ATEIS_Payload 内部的ATEIS_Payload 成员DNMManager_Ctor,您应该通过将结构放置在标头中来公开它,或者应该将此函数移到该结构已知的其他位置,或实现几个getter 函数,如Payload_getNamePayload_getSerialPayload_getSubnet 等。无论何时使用不透明的结构指针,都需要对其内部成员进行操作的外部函数。

标签: c information-hiding


【解决方案1】:

正如 Groo 所建议的,实现者必须向用户提供操作成员的功能。这是我的代码中的一个 sn-p:

uint32_t PayloadManager_GetAddr(ATEIS_Payload_s* this)
{
    return this->Addr;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 2020-08-27
    • 2012-01-12
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    相关资源
    最近更新 更多