I am trying to port a native C++ library to C++/CLI, so I can use it in C#. I am trying to figure out how to convert a few of the classes that basically lightly wrap a buffer for extracting fields. I’ve written a small sample to better describe what is going on in the API.
So, I have a Packet class that reads packets from a file:
#include <fstream>
#include <cassert>
#include "OptionalA.h"
class Packet
{
public:
Packet(void)
{
buffer = new char[PACKET_SIZE];
}
~Packet(void)
{
delete [] buffer;
}
void ReadNextPacket(std::ifstream& fileStream)
{
fileStream.read(buffer, PACKET_SIZE);
}
bool HasOptionalA()
{
return (buffer[0] & 0x1) == 1;
}
OptionalA GetOptionalA()
{
assert(HasOptionalA());
return OptionalA(&buffer[1], &buffer[1] + OptionalA::OPTIONAL_A_SIZE);
}
private:
const static int PACKET_SIZE = 3;
char* buffer;
};
The Packet I created has a very simple format:
[Packet: <Header Byte> [OptionalA: <Field1><Field2>]]
The OptionalA class is defined as follows:
#pragma once
#include <cassert>
class OptionalA
{
public:
static const int OPTIONAL_A_SIZE = 2;
OptionalA(const char* begin = 0, const char* end = 0) :
begin(begin), end(end)
{
assert((end - begin) == OPTIONAL_A_SIZE);
}
char GetField1()
{
return begin[0];
}
char GetField2()
{
return begin[1];
}
private:
const char* begin;
const char* end;
};
What is the correct way to wrap this type of class architecture such that I duplicate the minimum amount of memory in C++/CLI?
a simple way, but somewhat time consuming depending on the amount of classes you have to convert, is to create CLI wrappers that contain a native pointer to the type they wrap:
To spice things up and make better code, consider using something like this instead of raw native pointers and get cleanup for free. Also maybe consider using std::string and passing iterators around instead of raw char pointers, it’s C++ after all.