作者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://www.ptt.cc/bbs/C_and_CPP/M.1524992127.A.825.html
噓 KanzakiHAria: 原文是說為什麼要分開? 不分開會發生什麼事? 04/29 19:46
推 CoNsTaR: 然後這篇的原文是說他有心得可以分享怎麼做 05/03 06:58
→ adrianshum: 一來和前文無關,二來這根本就是(無用化了的)pimpl, 05/04 08:22
→ adrianshum: 三來C# 的 interface 根本就完全不是這回事 05/04 08:22
→ adrianshum: (還是收回第二點。和pimpl 還是有差) 05/04 08:28