user1562343
user1562343

Reputation: 33

Reusing structs from C in C#

Is it possible to import in C# structs definitions from C dlls?

In all the examples I saw were to redefine the structs in C#. What if the struct changes? I need to alter in two locations in my project...

struct MyCStruct
{
    unsigned long A;
    unsigned long B;
    unsigned long C;
};

and in C#:

    [StructLayout(LayoutKind.Sequential)]
    internal struct MyCStructAgain
    {
        public uint A;
        public uint B;
        public uint C;
    }

If It's not possible to reuse the definitions, why is that?

Thanks

Upvotes: 3

Views: 494

Answers (1)

Alois Kraus
Alois Kraus

Reputation: 13545

You could compile your structs as C++/CLI where the compiler generates the managed counterparts for you and you can reference them then. You would need an ifdef to prepend value to make it a .NET struct.

#ifdef CLIEXPORT
#define value
#endif

CLIEXPORT struct MyCStruct
{
    unsigned long A;
    unsigned long B;
    unsigned long C;
};

Upvotes: 2

Related Questions