Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

SOIL(Simple OpenGL Image Library) - Native DLL 및 .NET DLL 제공

아래의 라이브러리를,

Simple OpenGL Image Library
; https://www.lonesock.net/soil.html

Visual Studio 2017 환경에서 빌드하는 경우 _CRT_SECURE_NO_WARNINGS 관련한 경고와,

warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

"warning C4018: '>': signed/unsigned mismatch" 정도만 발생합니다. 그래도 ^^ 이런 경고조차도 보기 싫은 분들은 가볍게 소스 코드를 수정하면 됩니다.

우선, fopen을 fopen_s로 바꿔야 하는데, 이를 위해 errno 상수를 결과 값으로 다음과 같이 수정해 주면 됩니다.

// 수정 전
float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
{
    FILE *f = fopen(filename, "rb");
    float *result;
    if (!f) return epf("can't fopen", "Unable to open file");
    result = stbi_loadf_from_file(f, x, y, comp, req_comp);
    fclose(f);
    return result;
}

// 수정 후
float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
{
    FILE *f = NULL;
    errno_t err = fopen_s(&f, filename, "rb");
    float *result;
    if (err != 0) return epf("can't fopen", "Unable to open file");
    result = stbi_loadf_from_file(f, x, y, comp, req_comp);
    fclose(f);
    return result;
}

또한 "warning C4018"에 대해서는 적절하게 다음과 같은 식으로 형변환 연산자를 사용하면 됩니다.

// 수정 전
if( ref_x + 4 > s->img_x )
{
    bw = s->img_x - ref_x;
}

// 수정 후
if( (uint32)ref_x + 4 > s->img_x )
{
    bw = s->img_x - ref_x;
}




soil 프로젝트를 빌드하면 정적 링크 파일(.lib)이 생성되는데 이를 동적 링크 파일(.dll)로 바꾸고 싶을 수 있습니다. 그런데 이런 경우 예전에 언급했던 DLL 사용 관련한 주의를 해야 합니다.

DLL에 정의된 C++ template 클래스의 복사 생성자 문제
; https://www.sysnet.pe.kr/2/0/11153

문제는 soil 프로젝트가 OpenGL DLL의 함수를 정적 링크해서 사용한다는 점입니다. (그래서 vcpkg 등으로 opengl 라이브러리를 정적 빌드해 놓아야만 합니다.) 관련 함수의 목록은 다음과 같은데,

glBindTexture
glDeleteTextures
glGenTextures
glGetIntegerv
glGetString
glReadPixels
glTexImage2D
glTexParameteri
wglGetProcAddress

(제가 OpenGL을 잘 모르는데) 빌드한 soil 프로젝트가 정적 링크한 OpenGL 라이브러리와, soil DLL이 링크될 대상 EXE가 사용할 OpenGL 라이브러리의 버전이 다른 경우 문제가 없을 것인지 장담할 수가 없습니다.

해 보고, 문제없는지 확인하는 것도 가능하겠지만 이런 미심쩍은 부분은 애당초 그 원인을 없애는 것이 더 좋습니다. 다행이라면, 9개 정도의 함수밖에 사용하지 않아서 이것을 동적 로딩으로 바인딩하는 것도 좋은 해결책이 될 수 있습니다. 따라서 다음과 같이 Initialize 함수를 만들고,

// soil.c

typedef WINGDIAPI void (APIENTRY *glBindTextureFunc)(GLenum target, GLuint texture);
glBindTextureFunc _glBindTexture;

typedef WINGDIAPI void (APIENTRY *glDeleteTexturesFunc)(GLsizei n, const GLuint *textures);
glDeleteTexturesFunc _glDeleteTextures;

typedef WINGDIAPI void (APIENTRY *glGenTexturesFunc)(GLsizei n, GLuint *textures);
glGenTexturesFunc _glGenTextures;

typedef WINGDIAPI void (APIENTRY *glGetIntegervFunc)(GLenum pname, GLint *params);
glGetIntegervFunc _glGetIntegerv;

typedef WINGDIAPI const GLubyte * (APIENTRY *glGetStringFunc)(GLenum name);
glGetStringFunc _glGetString;

typedef WINGDIAPI void (APIENTRY *glReadPixelsFunc)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
glReadPixelsFunc _glReadPixels;

typedef WINGDIAPI void (APIENTRY *glTexImage2DFunc)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
glTexImage2DFunc _glTexImage2D;

typedef WINGDIAPI void (APIENTRY *glTexParameteriFunc)(GLenum target, GLenum pname, GLint param);
glTexParameteriFunc _glTexParameteri;

typedef WINGDIAPI PROC  (WINAPI *wglGetProcAddressFunc)(LPCSTR);
wglGetProcAddressFunc _wglGetProcAddress;

BOOL SOIL_Initialize(wchar_t *openglDLLFileName)
{
    HMODULE hModule = LoadLibrary(openglDLLFileName);

    if (hModule == NULL)
    {
        return FALSE;
    }

    _hModule = hModule;

    _glBindTexture = (glBindTextureFunc)GetProcAddress(hModule, "glBindTexture");
    _glDeleteTextures = (glDeleteTexturesFunc)GetProcAddress(hModule, "glDeleteTextures");
    _glGenTextures = (glGenTexturesFunc)GetProcAddress(hModule, "glGenTextures");
    _glGetIntegerv = (glGetIntegervFunc)GetProcAddress(hModule, "glGetIntegerv");
    _glGetString = (glGetStringFunc)GetProcAddress(hModule, "glGetString");
    _glReadPixels = (glReadPixelsFunc)GetProcAddress(hModule, "glReadPixels");
    _glTexImage2D = (glTexImage2DFunc)GetProcAddress(hModule, "glTexImage2D");
    _glTexParameteri = (glTexParameteriFunc)GetProcAddress(hModule, "glTexParameteri");
    _wglGetProcAddress = (wglGetProcAddressFunc)GetProcAddress(hModule, "wglGetProcAddress");

    if (_glBindTexture == NULL
        || _glDeleteTextures == NULL
        || _glGenTextures == NULL
        || _glGetIntegerv == NULL
        || _glGetString == NULL
        || _glReadPixels == NULL
        || _glTexImage2D == NULL
        || _glTexParameteri == NULL
        || _wglGetProcAddress == NULL)
    {
        return FALSE;
    }

    return TRUE;
}

함수를 동적으로 바인딩한 _glBindTexture 등의 함수 포인터를 사용하도록 소스 코드를 변경할 수 있습니다. 그렇게 되면 현재 프로세스에 로딩된 OpenGL DLL(예: opengl32.dll)의 함수를 사용하게 되므로 메모리 할당/해제 등의 불일치를 걱정할 필요가 없습니다.

이런 변경을 반영해 만든 라이브러리가 바로 SoilDotnet입니다.

SoilDotnet 1.0.1 
; https://www.nuget.org/packages/SoilDotnet

stjeong/SoilNET 
; https://github.com/stjeong/SoilNET

NuGet에 있기 때문에 당연히 Visual Studio의 NuGet Package Manager에서 설치할 수 있고,

Install-Package SoilDotnet

사용법은, 여러분들의 프로그램에서 opengl32.dll이 올라온 시점이라면 어느 때든지 다음과 같이 Initialize 메서드를 호출한 후,

private void glControl_ContextCreated(object sender, OpenGL.GlControlEventArgs e)
{
    // ...[omitted for brevity]...

    bool result = Soil.NET.WrapSOIL.Initialize();
    if (result == false)
    {
        MessageBox.Show("SOIL: Not initialized: " + Soil.NET.WrapSOIL.GetSoilLastError());
        return;
    }

    // ...[omitted for brevity]...
}

Texture 자원을 다음과 같이 로드해 주면 됩니다.

public uint loadTexture(string fileName)
{
    string filePath = $".\\res\\{fileName}.png";

    uint tex2d_id = Soil.NET.WrapSOIL.load_OGL_texture(filePath,
        Soil.NET.WrapSOIL.SOIL_LOAD.AUTO, Soil.NET.WrapSOIL.SOIL_NEW.ID,
        Soil.NET.WrapSOIL.SOIL_FLAG.MIPMAPS | Soil.NET.WrapSOIL.SOIL_FLAG.INVERT_Y | 
        Soil.NET.WrapSOIL.SOIL_FLAG.NTSC_SAFE_RGB | Soil.NET.WrapSOIL.SOIL_FLAG.COMPRESS_TO_DXT);

    _textures.Add(tex2d_id);
    return tex2d_id;
}

제가 사용하는 Soil 라이브러리의 함수가 SOIL_load_OGL_texture 하나뿐이라서 일단 그것만 구현한 상태입니다. 혹시 그 외의 다른 함수(SOIL_load_OGL_texture, ...)들이 필요하다면 이슈(https://github.com/stjeong/SoilNET/issues)로 올려 주세요. ^^ 반영해서 NuGet에 업데이트하겠습니다. (혹은, 소스 코드 변경해서 PR 넣으셔도 됩니다. ^^)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/13/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11833정성태3/4/201921005개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201916949오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916752오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916454오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918176개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926074개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919032오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919216오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924405개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201918839오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920606오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201918858오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919624오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922682오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201921974Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920005VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916383오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919791Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918044오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201916866오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918291.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915548오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920700오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201918461.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201920541.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201921869디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...