作者dzwei (-v暁ogc妹v-)
看板C_and_CPP
标题Re: [问题] 请问C介面跟实作分开的作法
时间Sun Apr 29 16:55:22 2018
刚好最近有碰到,
目前也还在学习中,
刚好有点小心得,
有错误还恳请版上的大师们指正,
谢谢!
提个关键字跟板友分享一下
『opaque pointer』
这跟C++的pimpl有87%像
以下code举例於维基百科
//=========================================
/* obj.h */
struct obj;
/*
* The compiler considers struct obj an incomplete type.
* Incomplete types can be used in declarations.
*/
size_t obj_size(void);
void obj_setid(struct obj *, int);
int obj_getid(struct obj *);
//--------------------------------------------
//--------------------------------------------
//--------------------------------------------
/* obj.c */
#include "obj.h"
struct obj {
int id;
};
/*
* The caller will handle allocation.
* Provide the required information only
*/
size_t obj_size(void) {
return sizeof(struct obj);
}
void obj_setid(struct obj *o, int i) {
o->id = i;
}
int obj_getid(struct obj *o) {
return o->id;
}
//=========================================
基本上这种机制很像C#的interface
(get/set)
再加个new/delete函式
就是一个完整的Obj wapper了
--
我老婆-娜琏,不服出来湾阿
https://imgur.com/ET5Oddy
https://imgur.com/Xz8gs6N
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 120.105.133.181
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1524992127.A.825.html
1F:嘘 KanzakiHAria: 原文是说为什麽要分开? 不分开会发生什麽事? 04/29 19:46
2F:推 CoNsTaR: 然後这篇的原文是说他有心得可以分享怎麽做 05/03 06:58
3F:→ adrianshum: 一来和前文无关,二来这根本就是(无用化了的)pimpl, 05/04 08:22
4F:→ adrianshum: 三来C# 的 interface 根本就完全不是这回事 05/04 08:22
5F:→ adrianshum: (还是收回第二点。和pimpl 还是有差) 05/04 08:28