티스토리 뷰

아래 내용은 p. 93 ~ 107에 해당됨.

 

1)  엠스크립튼의 조건부 컴파일 심볼과 헤더 파일

웹어셈블리 모듈 개발을 하려면 엠스크립튼 헤더 파일을 코드에 추가해야 함.

조건부 컴파일 심볼(conditional compilation symbol)인 __EMSCRIPTEN__  을 통해 컴파일하는지 여부를 알 수 있음.

엠스크립튼으로 컴파일하지 않을 때 필요한 헤더 파일은 조건부 파일 심볼의 else에 넣으면 됨.

더보기
#include <cstdlib>
#include <cstring>

#ifdef __EMSCRIPTEN__ // 심볼
	// 엠스크립튼 라이브러리 헤더 파일
	#include <emscripten.h> 
#endif

 

2) Extern "C" 블록

코드를 컴파일 할 때 함수명이 죽복되지 않게 바꿈. 이를 네임 맹글링(name mangling)이라 함.

이로 인해 외부 코드에서 특정 함수를 호출할 경우 임의로 변경된 함수명 때문에 찾을 수 없게 됨.

이를 방지하기 위해 c++ 함수를 호출 할 때 함수 주변을 extern "C" 블록으로 감싸야 함.

더보기
#ifdef __cplusplus
extern "C" {
#endif

// 함수 작성하는 곳

#ifdef __cplusplus
}
#endif

 

 

3) 함수 작성하는 곳에 함수 작성

상세 함수는 아래 완성된 코드에서 확인 요망

 

 

4) 코드를 웹어셈블리 모듈로 컴파일

책 내용대로 했는데 컴파일이 안 되서 당황했음.

컴파일 방법은 여기를 참고하면 됨.

컴파일 후 생성된 파일 확인

 

완성된 c++ 코드

더보기
#include <cstdlib>
#include <cstring>

#ifdef __EMSCRIPTEN__
	#include <emscripten.h>
#endif

#ifdef __cplusplus
extern "C" {
#endif

int ValidateValueProvided(const char* value, const char* error_message, char* return_error_message) {
	if((value == NULL) || (value[0] == '\0')) {
		strcpy(return_error_message, error_message);
    return 0;
	}
	return 1;
}

#ifdef __EMSCRIPTEN__
EMSCRIPTEN_KEEPALIVE
#endif
int ValidateName(char* name, int maximum_length, char* return_error_message) {
	if (ValidateValueProvided(name, "A Produc Name must be provided.", return_error_message) == 0) {
		return 0;
	}

	if (strlen(name) > maximum_length) {
		strcpy(return_error_message, "The Product Name is too long.");
		return 0;
	}
	return 1;
}

int IsCategoryIdInArray(char* selected_category_id, int* valid_category_ids, int array_length) {
	int category_id = atoi(selected_category_id);
	for (int index = 0; index < array_length; index++) {
		if (valid_category_ids[index] == category_id) {
			return 1;
		}
	}
	return 0;
}


#ifdef __EMSCRIPTEN__
EMSCRIPTEN_KEEPALIVE
#endif
int ValidateCategory(char* category_id, int* valid_category_ids, int array_length, char* return_error_message) {
	if (ValidateValueProvided(category_id, "A Product Category must be selected.", return_error_message) == 0) {
		return 0;
	}

	if ((valid_category_ids == NULL) || (array_length == 0)) {
		strcpy(return_error_message, "There are no Product Categories available.");
		return 0;
	}

	if (IsCategoryIdInArray(category_id, valid_category_ids, array_length)==0){
		strcpy(return_error_message, "The selected Product Category is not valid."); return 0;
		return 0;
	}

	return 1;
}
#ifdef __cplusplus
}
#endif

작성된 파일

 

 

끝!

반응형
LIST
댓글
링크
공지사항
최근에 올라온 글