Created
November 4, 2020 20:56
C++/CLI wrap example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ISO C++ | |
#pragma once | |
class Base { | |
private: | |
int m_SomeInt; | |
public: | |
inline int getInt() const { | |
return m_someInt; | |
} | |
inline void setInt(int someOtherInt) { | |
m_SomeInt = someOtherInt; | |
} | |
Base() {} | |
virtual ~Base() = default; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C++/CLI | |
#include "Base.h" | |
#include "ManagedObject.h" | |
/* | |
* This code creates a class that can be used in .NET | |
*/ | |
public ref class Base { | |
public: | |
inline int^ getInt() { | |
// the ^ accent allows the C++/CLI know that it's a .NET object | |
return get_instance()->getInt(); | |
} | |
inline void setInt(int^ newInt) { | |
get_instance()->setInt(*newInt); // here we derreference the pointer to access the int | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C++/CLI | |
#pragma once | |
using namespace System; | |
namespace Interop | |
{ | |
template <class T> | |
public ref class ManagedObject | |
{ | |
protected: | |
T* m_Instance; | |
public: | |
explicit ManagedObject(T* instance) | |
: m_Instance(instance) { } | |
virtual ~ManagedObject() | |
{ | |
if (m_Instance != nullptr) { | |
delete m_Instance; | |
} | |
} | |
!ManagedObject() | |
{ | |
if (m_Instance != nullptr) { | |
delete m_Instance; | |
} | |
} | |
T* get_instance() | |
{ | |
return m_Instance; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment