设为首页 加入收藏

TOP

C++ 项目中的extern "C" (四)
Tags:项目 extern " C"
id f(char* v,int sz)
{
//error,as qsort is style of C
//but compare is style of C++(www.cppentry.com)
qsort(v,sz,1,&compare);
qsort(v,sz,1,&ccomp);//ok

isort(v,sz,1,&compare);//ok
//error,as isort is style of C++(www.cppentry.com)
//but ccomp is style of C
isort(v,sz,1,&ccopm);
}
int (*FT) (
01
typedef
const
void
* ,const void*);//style of C++(www.cppentry.com)
 
02
 
"C"{
03
extern
typedefint
04
    
(*CFT) (
const void*,const void*);//style of C
voidqsort
05
    
(
void* p,size_t n,size_t sz,CFT cmp);//style of C
06
}
 
07
 
isort(void
08
void
* p,
size_t n,size_t sz,FT cmp);//style of C++(www.cppentry.com)
xsort(void
09
void
* p,
size_t n,size_t sz,CFT cmp);//style of C
 
10
 
11
//style of C
"C"void
12
extern
ysort(
void* p,size_t n,size_t sz,FT cmp);
 
13
 
compare(const
14
int
void
*,const void*);//style of C++(www.cppentry.com)
"C" ccomp(
15
extern
const
void*,const void*);//style of C
 
16
 
f(char
17
void
* v,
int sz)
18
{
//error,as qsort is style of C
19
    
//but compare is style of C++(www.cppentry.com)
20
    
qsort(v,sz,1,&compare);
21
    
qsort(v,sz,1,&ccomp);
22
    
//ok
 
23
     
isort(v,sz,1,&compare);//ok
24
    
//error,as isort is style of C++(www.cppentry.com)
25
    
//but ccomp is style of C
26
    
isort(v,sz,1,&ccopm);
27
    
28
}

注意:typedef int (*FT) (const void* ,const void*),表示定义了一个函数指针的别名FT,这种函数指针指向的函数有这样的特征:返回值为int型、有两个参数,参数类型可以为任意类型的指针(因为为void*)。

最典型的函数指针的别名的例子是,信号处理函数signal,它的定义如下:

void (*HANDLER)(
1
typedef
int
);
signal(
2
HANDLER
int
,HANDLER);

上面的代码定义了信函处理函数signal,它的返回值类型为HANDLER,有两个参数分别为int、HANDLER。 这样避免了要这样定义signal函数:

(*signal
1
void
(
int
,
void(*)(int) ))(int)

比较之后可以明显的体会到typedef的好处。

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇string类型与int,float类型转换 下一篇C++ 枚举子相关类型解析

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: