Converting unmanaged struct to .NET struct

  • Thread starter Thread starter Øystein Skotheim
  • Start date Start date
Ø

Øystein Skotheim

I want to interface some old C++ code and make a .NET interface called
StructuredPoints to a set of 3D points layed out on a rectangular grid
structure.

The C++ code uses a templated Matrix class to store the 3D points, like
this:

Matrix<Point3Df> *pts;

The Point3Df structure is also defined from a template like this:

typedef Point3D<float> Point3Df;

Individual points can be accessed like this from C++, e.g.

float _x = (*pts)[y][x].x;
float _y = (*pts)[y][x].y;
_x *= 2; _y *= 2;
(*pts)[y][x].x = _x;
(*pts)[y][x].y = _y;

Now I want to make a .NET interface which I have called
StructuredPoints. I want to define a default operator which returns a
handle or a reference to these points, so that I can read and write the
points with a minimum of overhead, e.g.

StructuredPoints^ spts;
float _x = spts[x,y].x; // . or -> operator
float _y = spts[x,y].y;
_x *= 2; _y *= 2;
spts[x,y].x = _x;
spts[x,y].y = _y;

I guess I have to define a new "ref struct" with an identical layout of
the unmanaged structure, something like this?

ref struct DotNetPoint3Df
{
float x;
float y;
float z;
};

(I have experimented with the #pragma make_public directive to make the
original Point3Df class visible for .NET languages, but it does not seem
to work for templated classes)

Then I embed this as a protected data member in my StructuredPoints ref
class:

ref class StructuredPoints
{
protected:
Matrix<Point3Df>* m_Points;
[...]
}

Now I want to define an indexer property that lets me access the points
and return them as a handle or a reference to a DotNetPoint3Df,
something like this:

property DotNetPoint3Df^ default[int,int]

I guess I need to cast or marshal the pointer to an instance of the
unmanaged Point3Df class (e.g. (*m_Points)[y][x]) to a handle to a
DotNetPoint3Df class? But how do I do that? (I would prefer not to copy
the values from the unmanaged structure to the managed structure,
because that seems expensive when I have to work with e.g. millions of
points)

Opinions on the best way to do this are appreciated :-)

Best regards,
 
Øystein Skotheim said:
I want to interface some old C++ code and make a .NET interface called
StructuredPoints to a set of 3D points layed out on a rectangular grid
structure.

The C++ code uses a templated Matrix class to store the 3D points,
like this:

Matrix<Point3Df> *pts;

The Point3Df structure is also defined from a template like this:

typedef Point3D<float> Point3Df;
[snip]


(I have experimented with the #pragma make_public directive to make
the original Point3Df class visible for .NET languages, but it does
not seem to work for templated classes)

Can you derive a new type instead of using typedef, ala
struct Point3Df : public Point3D<float> {};

and then use make_public?
 
Back
Top