首先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的头文件)spa
#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。code
-------------------------------------------以上为A代码,如下为B代码-------------------------------------------orm
B将A提供的头文件和lib文件加入工程。
string
B调用Lib的代码:
it
#include "Method.h" int main(int argc, char* agrv[]) { _MyStruct_t* pstMyStruct = stCreateStruct(10, "china"); vPrintf(pstMyStruct); free(pstMyStruct); return 0; }
------------------------------------------我是华丽的分割线------------------------------------------------------io
typedef struct _MyStruct _MyStruct_t 这句代码为B提供了使用结构体的定义,可是B只能使用结构体指针,而不能直接使用结构体,且没法接触到结构体中的成员,从而实现告终构体的不透明化。根据我的理解,这里用到的应该只是一个指针,不管什么指针均可以,即便定义成 typedef int _MyStruct_t,依然可以编译运行(VS下测试经过)。编译