学生時代とは異なり、企業で別々の部署でモジュールを開発している場合にインタフェースを定義し、呼び出して利用することが一般的です。
C++だとインターフェースクラスなどが存在しますが、C言語を利用した場合の一般的な例は次のとおりです。
スポンサードリンク
関数ポインタを利用して宣言されたインタフェースを呼び出して利用するサンプルソースコードです。
#include <stdio.h>
typedef struct Hoge_Interface {
int (*Func1)(void);
void (*Func2)(int num);
void (*Func3)(const char *chr);
} Hoge_Interface;
void CallModuleB(void* pInterface)
{
Hoge_Interface* pHoge = (Hoge_Interface*)pInterface;
// 各インターフェースを条件に応じて呼び出す
if (pHoge->Func1) pHoge->Func1();
else printf("Hoge->Func1 unread.\n");
if (pHoge->Func2) pHoge->Func2(12345);
else printf("Hoge->Func2 unread.\n");
if (pHoge->Func3) pHoge->Func3("hoge");
else printf("Hoge->Func3 unread.\n");
return;
}
int Hoge_Func1(void)
{
printf("%s()\n", __FUNCTION__);
return 0;
}
void Hoge_Func2(int num)
{
printf("%s() num = %d\n", __FUNCTION__, num);
return;
}
int main(void)
{
// インタフェースを定義する
// Func3 は利用しないとし、NULLとする
Hoge_Interface Hoge = {
Hoge_Func1,
Hoge_Func2,
NULL,
};
// インタフェースのポインタを渡す
CallModuleB(&Hoge);
// この関数から使う場合の例
Hoge.Func1();
Hoge.Func2(999);
return 0;
}
gcc IF_Test.cpp -lstdc++
スポンサードリンク
各関数が呼び出されることを確認できます。
$ ./a.out Hoge_Func1() Hoge_Func2() num = 12345 Hoge->Func3 unread. Hoge_Func1() Hoge_Func2() num = 999
スポンサードリンク