How to define struct with array in C#?

P

Polaris

Hi Experts:

In my C# program I need to use a Win32 DLL which leads to a question: how to
define Win32/C++ struct with array in C#. For example, I have a C++ struct:

struct MY_STRUCT
{
int nCities[128];
};

How to define it in C#?

Thanks in advance!
Polaris
 
J

Jon Skeet [C# MVP]

Polaris said:
In my C# program I need to use a Win32 DLL which leads to a question: how to
define Win32/C++ struct with array in C#. For example, I have a C++ struct:

struct MY_STRUCT
{
int nCities[128];
};

How to define it in C#?

The problem isn't declaring an array - it's declaring an array with a
fixed size. In C# 2 you can declare it in unsafe code with a fixed-size
buffer:

struct MY_STRUCT
{
fixed int nCitires[128];
}

However, in my experience it's not worth it - look at marshalling
options instead to get the marshaller to copy stuff for you. I don't
know a lot about interop like this I'm afraid, but the interop
newsgroup might be able to help you.
 
W

Willy Denoyette [MVP]

Polaris said:
Hi Experts:

In my C# program I need to use a Win32 DLL which leads to a question: how
to define Win32/C++ struct with array in C#. For example, I have a C++
struct:

struct MY_STRUCT
{
int nCities[128];
};

How to define it in C#?

Thanks in advance!
Polaris


internal struct MY_STRUCT
{
internal const int nrOfCities= 128;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = nrOfCities)]
internal int nCities[];
};

For more info search MSDN for "Marshaling Data with Platform Invoke"

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top