[C/C++]不透明结构体使用

首先A代码:

struct.h(A的结构体定义)

#ifndef __STRUCT_H__
#define __STRUCT_H__

typedef struct _MyStruct
{
	int iAge;
	char* pName;
}ST_MY_STRUCT,*PST_MY_STRUCT;

#endif

Method.h(A提供给B的头文件)

#ifndef __METHOD_H__
#define __METHOD_H__

typedef struct _MyStruct _MyStruct_t; //这里注意一下,下文中会解释这句话

void vPrintf(_MyStruct_t* pstMyStruct); //供B调用,输出结构体信息

_MyStruct_t* stCreateStruct(int iAge, const char* pName); //供B调用,生成结构体

#endif

Method.cpp(A函数实现)

#include "Method.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "struct.h"

void vPrintf(_MyStruct_t* pstMyStruct)
{
	if (!pstMyStruct)
	{
		printf("the struct is null\n");
		return;
	}
	printf("Age:%d----Name:%s\n", pstMyStruct->iAge, pstMyStruct->pName);
}

_MyStruct_t* stCreateStruct(int iAge, const char* pName)
{
	_MyStruct_t* pstMyStruct = (_MyStruct_t*)malloc(sizeof(_MyStruct_t));
	memset(pstMyStruct, 0, sizeof(_MyStruct_t));
	pstMyStruct->iAge = iAge;
	int iSize = strlen(pName) + 1;
	pstMyStruct->pName = (char*)malloc(iSize);
	memcpy(pstMyStruct->pName, pName, iSize);
	return pstMyStruct;
}

A将代码编译之后生成Lib文件(LibTest.lib),将Method.h和LibTest.lib两个文件提供给B。

-------------------------------------------以上为A代码,以下为B代码-------------------------------------------

B将A提供的头文件和lib文件加入工程。

B调用Lib的代码:

#include "Method.h"

int main(int argc, char* agrv[])
{
	_MyStruct_t* pstMyStruct = stCreateStruct(10, "china");
	vPrintf(pstMyStruct);
	free(pstMyStruct);
	return 0;
}


------------------------------------------我是华丽的分割线------------------------------------------------------

       typedef struct _MyStruct _MyStruct_t 这句代码为B提供了使用结构体的定义,但是B只能使用结构体指针,而不能直接使用结构体,且无法接触到结构体中的成员,从而实现了结构体的不透明化。根据个人理解,这里用到的应该只是一个指针,无论什么指针都可以,即使定义成 typedef int _MyStruct_t,依然能够编译运行(VS下测试通过)。


转载于:https://my.oschina.net/u/1429862/blog/225428

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值