window.google_render_ad(); 注:本文针对的是linux下C/C++编程,windows下原理应该一样,只是编译命令不同。
由于某些原因,你不想公开你的源码,只提供库文件给客户使用,而且不想让客户看到定义的数据结构,怎么办呢??C语言的不透明结构体句柄就派上用场了。
下面这个列子用来说明怎么实现不透明结构体,例子总共有四个文件:
type.h sstruct.h flib.c test.c。
sstruct.h 结构体定义头文件,自己编译时使用,不给客户隐藏结构体定义。
type.h 编译好的库文件函数接口说明和句柄定义,给客户使用。
flib.c 给客户的函数库文件,这里只编译成.o文件,再加一个编译命令就编译成 XX.a静态库 或者 XX.so动态库
test.c 模拟客户的主函数文件,客户通过type.h定义的接口调用flib.c编译好的库文件。
其中sstruct.h是定义结构体的头文件,只被库文件flib.c引用;而type.h则定义了库文件flib.c实现的函数和库文件的结构体句柄,库文件flib.c和test.c主函数文件都引用。四个文件代码如下:
//type.h
typedef struct _Life_t * MsgLife;
void func( MsgLife *life );
void freefunc( MsgLife *life );
//sstruct.h
#include
#include
typedef struct _Life_t
{
char ip[16];
unsigned short port;
}MsgLife_t;
//flib.c
#include "sstruct.h"
#include "type.h"
void func( MsgLife *life )
{
*life = NULL;
MsgLife_t *myl=NULL;
myl = (MsgLife)malloc( sizeof(MsgLife_t) );
myl->port = 5555;
strncpy( myl->ip, "255.255.255.255", 16 );
printf( "in func ip=%s port=%d/n", myl->ip, myl->port );
*life = myl;
return;
}
void freefunc( MsgLife *life )
{
MsgLife_t *myl=*life;
myl->port = 6666;
strncpy( myl->ip, "111.111.111.111", 16 );
printf("in freefunc ip=%s port=%d/n", myl->ip, myl->port );
free( myl );
*life = NULL;
printf("finished free the malloc point/n");
return;
}
将文件中间的注释去掉,编译就会报类似XX未声明的错误。
//test.c
#include "type.h"
int main()
{
MsgLife life;
func( &life );
// printf( "ip=%s port=%d/n", life->ip, life, port );
freefunc( &life );
return 1;
}
下面是编译命令,这里只是简单的将flib.c编译成flib.o文件,然后test.c主函数文件在编译的时候直接添加flib.o文件,跟编译添加静态库文件原理一样,只不过静态库打了一个包。实际应用当然是编译成静态库.a文件或者是动态库.so文件了。
cc -c flib.c -g
cc -o test test.c flib.o -g
运行结果如下:
[mgqw@localhost 123]$ ./test in func ip=255.255.255.255 port=5555in freefunc ip=111.111.111.111 port=6666finished free the malloc point