Skip to content

Instantly share code, notes, and snippets.

@ariel-avi
Created November 4, 2020 20:56
C++/CLI wrap example
// 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;
}
// 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
}
}
// 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