2016. 12. 23. 16:46
Binary-compatible C++ Interfaces
2016. 12. 23. 16:46 in link/language
Binary-compatible C++ Interfaces
// Window.h class Window { public: virtual void CALL destroy() = 0; virtual void CALL setTitle(const char* title) = 0; virtual const char* CALL getTitle() = 0; void operator delete(void* p) { if (p) { Window* w = static_cast<Window*>(p); w->destroy(); } } }; extern "C" Window* CALL CreateWindow(const char* title);
// Window.cpp #include <string> #include <windows.h> #include "DefaultDelete.h" class WindowImpl : public DefaultDelete<Window> { public: WindowImpl(HWND window) { m_window = window; } ~WindowImpl() { DestroyWindow(m_window); } void CALL destroy() { delete this; } void CALL setTitle(const char* title) { SetWindowText(m_window, title); } const char* CALL getTitle() { char title[512]; GetWindowText(m_window, title, 512); m_title = title; // save the title past the call return m_title.c_str(); } private: HWND window; std::string m_title; }; Window* CALL CreateWindow(const char* title) { // create the Win32 window object HWND window = ::CreateWindow(..., title, ...); return (window ? new WindowImpl(window) : 0); }// DefaultDelete.h
template<typename T> class DefaultDelete : public T { public: void operator delete(void* p) { ::operator delete(p); } };