함수들을 감싸는 wrapper 함수를 생성하겠습니다.
구조체 내에 함수 포인터 인자를 설정합니다.
예시로, wrap1.c와 wrap2.c의 함수를 만들겠습니다.
다음과 같은 구조체를 생성하여 wrap1, wrap2 파일 내에 모든 함수를 변수로 받습니다.
struct Wrapper
{
int version
#include "wrap1.h"
#include "wrap2.h"
}
사용할 매크로는 다음과 같습니다.
#define DECLARE_FUNCTION(returnType, name)\
returnType name
#define DECLARE_FUNCTION_POINTER(returnType, name)\
returnType (* name)
테스트할 함수를 다음과 같이 만들어봅니다.
#ifndef __WRAP1_H__
#define __WRAP1_H__
#define DECLARE_FUNCTION(returnType, name)\
returnType name
#define DECLARE_FUNCTION_POINTER(returnType, name)\
returnType (* name)
#else // __WRAP1_H_
INFO_FUNCTION(int, test1)
#ifndef WRAPPER_NOT_NEED
(int);
#endif
#endif
#ifndef __WRAP2_H__
#define __WRAP2_H__
#include "wrap1.h"
#else//__WRAP2_H_
INFO_FUNCTION(int, test2)
#ifndef WRAPPER_NOT_NEED
(void);
#endif
#endif
wrap1, wrap2 함수는 간단하게 만들어 보겠습니다.
더보기
/* wrap1.c */
#include "wrap1.h"
#include <stdio.h>
DECLARE_FUNCTION(int, test1)(int a)
{
printf("input %d, %s \n", a, __FUNCTION__);
return 1;
}
/* wrap2.c */
#include "wrap2.h"
#include <stdio.h>
DECLARE_FUNCTION(int, test2)(void)
{
printf("%s \n", __FUNCTION__);
return 1;
}
이제 두 파일의 함수를 결합합니다. 새로운 wrapper.h 파일입니다.
더보기
#ifndef __WRAPPER_H__
#define __WRAPPER_H__
#define INFO_FUNCTION(returnType, name)\
DECLARE_FUNCTION(returnType, name)
#include "wrap1.h"
#include "wrap2.h"
struct Wrapper;
int check (struct Wrapper * list);
#undef INFO_FUNCTION
#define INFO_FUNCTION(returnType,name) \
typedef DECLARE_FUNCTION_POINTER(returnType, Test_##name)
#include "wrap1.h"
#include "wrap2.h"
#undef INFO_FUNCTION
#define INFO_FUNCTION(returnType, name) \
Test_##name name;
#define WRAPPER_NOT_NEED 1
struct Wrapper
{
int version;
#include "wrap1.h"
#include "wrap2.h"
};
#undef WRAPPER_NOT_NEED
#undef INFO_FUNCTION
#define INFO_FUNCTION(returnType, name)\
DECLARE_FUNCTION(returnType, name)
#include "wrap1.h"
#include "wrap2.h"
#endif
모든 설정이 마무리되었습니다. wrapper 함수를 사용하여 결과를 확인해봅니다.
#include "wrapper.h"
#include <stdio.h>
int check(struct Wrapper * list)
{
(list) ->version = 2;
list->test1 = test1;
list->test2 = test2;
return 1;
}
int main()
{
struct Wrapper tmp;
int a = 100;
check(&tmp);
tmp.test1(a);
tmp.test2();
return 1;
}
다음과 같은 결과를 확인할 수 있습니다.
input 100, test1
test2
헤더 파일을 순차적으로 읽어보시는 걸 추천드립니다.
'개발' 카테고리의 다른 글
linux kernel, vscode 연동 (0) | 2020.12.03 |
---|---|
ulimit 명령어와 Select, Poll 함수 (0) | 2020.10.12 |
The file couldn’t be opened because you don’t have permission to view it. (0) | 2020.10.07 |
호출 규약 (0) | 2020.09.22 |
PFX 인증서 생성 (0) | 2020.06.19 |