Graviton
Graviton

Reputation: 83254

Does Returning Structure with Pointers in Interop Take a lot of Memory Space?

I have the following structure in c++:

#define CGAPI_Exports_Attr __declspec(dllimport)
extern "C"CGAPI_Exports_Attr  struct PointCg
    {
        double x;
        double y;


    };

extern "C"CGAPI_Exports_Attr struct PolylineCg
{
    int num_points;
    PointCg *points;

};

And the interop method goes like this:

extern "C"CGAPI_Exports_Attr PolylineCg ConstructPolyline();

The question is, for efficiency and memory purpose, should I return PolylineCg as shown above, or should I pass in PolylineCg parameter and let it be filled inside the ConstructPolyline method?

Upvotes: 0

Views: 127

Answers (1)

joncham
joncham

Reputation: 1614

I'll answer assuming x64.

Theoretically, it doesn't matter. If you return the PolylineCg, the size of the struct is greater than 64-bits. This means the value will not fit in the return register (64-bit RAX register), and it cannot be returned by value. This means enough space needs to be allocated for the return value, and the return register will point to that allocated space.

Conversely, if you pass the PolylineCg argument into the ConstructPolyline call via an out/ref parameter the same will be true. The value has to be passed by reference via a ref/out parameter, and should incur the same overhead.

Both methods should have the same efficiency, and the memory overhead will be minimal since you are using a value type.

Upvotes: 1

Related Questions