gpt4 book ai didi

c - 从不同的文件访问 C 结构成员(主要)

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:27 24 4
gpt4 key购买 nike

检查了几个堆栈溢出问题/答案,但没有一个符合我正在尝试做的事情。这是它:

我有一个 c 目标文件 myobject.c 包含在运行时填充的结构类型(由具有 main() 函数的主文件初始化。下面是骨架结构myobject.c 的:

typedef struct
{
uint16_t ID;
float tempo;
char unit[10];
unsigned long timestamp;
} prv_data_t;

static uint8_t prv_value(lwm2m_data_t* dataP,
prv_data_t* tempData)
{
uint8_t ret = COAP_205_CONTENT;
//TO DO here
.
.
.
return ret;
}

static uint8_t prv_read(..paramList)
{
//TO DO here
.
.

//then call prv_value here
result = prv_value((*tlvArrayP)+i, tempData);

return result;
}
object_t * get_object(){
//this func get called by main.c to initialize myobject
}

main.c文件的骨架结构:

myFunc(mypar p) {

}

main(){

//initialize myobject
//.....

//access myobject struct member here, pass to myFunc call
myFunc(tempo)
}

main.c 初始化myobject.c。现在我想从 myobject.c 访问 tempoprv_data_t 成员进行一些计算。如何在不在 main.c 中公开 prv_data_t 的情况下完成这样的任务?

编辑:这就是我所说的 main.c 初始化 myobject.c 和所有其他对象的意思,请:

 /*
* Now the main function fill an array with each object,
* Those functions are located in their respective object file.
*/
objArray[0] = get_security_object();
if (NULL == objArray[0])
{
fprintf(stderr, "Failed to create security object\r\n");
return -1;
}
.
.
.

主文件实际上包含main()函数。

最佳答案

您可以通过以下方式避免暴露您的私有(private)数据:

  1. main 使用指向不完整类型的指针 struct prv_data_t

  2. 为您允许 main 访问的成员实现 getter 函数(和 setter 函数)

像这样:

啊.h

#include <stdio.h>

struct prv_data_t; // Incomplete type

struct prv_data_t * get_obj();
float get_tempo(struct prv_data_t * this);

交流

#include <stdio.h>
#include <stdlib.h>

struct prv_data_t
{
int ID;
float tempo;
char unit[10];
unsigned long timestamp;
};

float get_tempo(struct prv_data_t * this)
{
return this->tempo;
}

struct prv_data_t * get_obj()
{
struct prv_data_t * p = malloc(sizeof *p);

p->tempo = 42.0;

return p;
}

ma​​in.c

#include <stdio.h>
#include "a.h"

int main()
{
struct prv_data_t * p = get_obj();

printf("%f\n", get_tempo(p));

// The line below can't compile because the type is incomplete
// printf("%f\n", p->tempo);

return 0;
}

所以对于这种代码,main 只知道存在一个struct prv_data_tmain 对那个结构的成员一无所知。

关于c - 从不同的文件访问 C 结构成员(主要),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54809655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com