Filexaura
Filexaura

Reputation: 15

Using C library with different data structure

I have a question about the best way to write computing code as flexible as possible in C++, I give you this example:

I am writing a code that manipulates meshes (Finite Element computation), basically set of nodes and connectivities. We only focus on Node structure for now:

struct Node { double x,y,z; };

I have a set of algorithm implemented using this Node data structure.

However I want to use an external library that provides specific geometrical treatment on meshes (writen by a collegue), it has a different data structure for Node

struct LibNode { double x; int idx; double y,z;};

note: int idx is used in the library, I do not need/want it in my own developpement.

All the algorithms of this library are written with this structure. I am just using the library, for me it is just a set of treatment that I can apply to the mesh I am using for computing.

I want to use the algorithm in the library written in C, so here are the solutions I imagine:

I have several questions here:

Thank you in advance for your response !

Upvotes: 1

Views: 101

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148890

If your code is conformant C, the simplest way would be to rebuild the library using Node, just changing Node to struct Node { double x; int idx; double y,z;};. All access to members x, y and z should work correctly, and the idx node will be processed more or less as padding. After all, that is one of the best points on using structs for maintaining applications: you can add members with no or little change to existing code

Of course if you assume somewhere that &node.y == &node.x + 1 everything will break...

The only thing I can think about that could be problematic would be loading structs that would have been saved as a whole to a binary file. That part (and the save part) should be rewritten to explicitely save and restore members and not the whole whole struct - anyway saving a whole struct is non portable and should be avoided if possible.

Another problem, mainly if it is used as a DLL, is that it will be a major change because it will break compatibility, so you should considere to rebuild all programs using your library.

Upvotes: 2

Related Questions