Disclaimer: The author of this post is a C++ beginner.
In my Erlang code, I have a data structure which represents a directed graph:
-record(vertex_entry, {vertex_name, outgoing_edges}).
-record(outgoing_edge, {edge_weight, neighbour_name}).
Edge1 = #outgoing_edge{edge_weight = 12.5, neighbour_name = 2},
Edge2 = #outgoing_edge{edge_weight = 11.2, neighbour_name = 3},
Edges = [Edge1,Edge2],
Vertex1 = #vertex_entry{vertex_name = 1, outgoing_edges = Edges},
Vertex4 = #vertex_entry{vertex_name = 4, outgoing_edges = Edges},
Graph = [Vertex1,Vertex4].
I would like to pass this graph to C++ through the Erlang’s port functionality.
On the C++ side I would like to convert this Erlang graph to a graph of the following structure (it is a CUDA-optimized adjacency list structure):
typedef struct
{
// (V) This contains a pointer to the edge list for each vertex
int *vertexArray;
// Vertex count
int vertexCount;
// (E) This contains pointers to the vertices that each edge
// is attached to
int *edgeArray;
// Edge count
int edgeCount;
// (W) Weight array
float *weightArray;
} GraphData;
Perhaps, the C++ graph generation code from the same source (Chapter 16 of the book) would be helpful to solve the issue:
void generateRandomGraph(GraphData *graph, int numVertices, int neighborsPerVertex)
{
graph->vertexCount = numVertices;
graph->vertexArray = (int*) malloc(graph->vertexCount * sizeof(int));
graph->edgeCount = numVertices * neighborsPerVertex;
graph->edgeArray = (int*)malloc(graph->edgeCount * sizeof(int));
graph->weightArray = (float*)malloc(graph->edgeCount * sizeof(float));
for(int i = 0; i < graph->vertexCount; i++)
{
graph->vertexArray[i] = i * neighborsPerVertex;
}
for(int i = 0; i < graph->edgeCount; i++)
{
graph->edgeArray[i] = (rand() % graph->vertexCount);
graph->weightArray[i] = (float)(rand() % 1000) / 1000.0f;
}
}
I assume that the Erlang’s ports functionality will help me to pass the data from Erlang to C++ in a binary format.
So, the question is:
How do I recover and convert a certain Erlang data structure (which represents a graph) into the aforementioned user-specified C++ graph data structure in C++ code?
Unless performance is critical here, consider serialising to text instead, in a format which is easy to parse. It’ll save you lots of debugging effort if you can read the output, save it to file when testing the read side, etc.
Even if you do decide to switch to a binary encoding, writing out the text encoding first might help decide the layout. My response to your other question should give you a pointer on the basics of reading binary, instead of text input, on the C++ side.
Also, if you’re relatively new to C++, you might as well start out with good idiomatic style if possible: consider replacing your
int*arrays and manual allocations withstd::vector<int>, etc.