Unsafe pointers

A

Abra

Hi,

I try to compile the following code (Visual Studio .NET 2005) :

....
somedata = new Byte[1024];

unsafe
{
fixed ( byte *pData = somedata)
{
MY_STRUCT1* ptr = (MY_STRUCT1*)pData;
}
...

, but I get the following error mesasge from compiler :

Error 38 Cannot take the address of, get the size of, or declare a
pointer to a managed type MY_STRUCT1 ...

on the line with the assignment of the ptr pointer.

Here is how MY_STRUCT1 looks like :

[Serializable]
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct MY_STRUCT1 {
int par1;
int par2;

[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public byte [] abParamVal;
}

If I dont have the line with the abParamVal byte-array in the structure,
everything is fine for the compiler.

Can someone please explain why this does not work ?

Thanks in advance.
Abra
 
M

Mattias Sjögren

Can someone please explain why this does not work ?

The compiler pretty much told you why. You can only use pointers to
primitive value types and structs made up of such types. You can't use
any reference types, including arrays.

Since you're using C# 2.0 you can use the fixed array syntax instead

public unsafe struct MY_STRUCT1 {
int par1;
int par2;
fixed byte abParamVal[8];
}


Mattias
 
N

Nicholas Paldino [.NET/C# MVP]

Abra,

The reason this does not work is because the array is not embedded in
the structure, so it would treat the four bytes at that address location as
a pointer, which isn't really what you want.

If you are using C#, you should be able to do this:

[Serializable]
[StructLayout(LayoutKind.Sequential, Pack=1)]
public unsafe struct MY_STRUCT1 {
int par1;
int par2;

[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public fixed byte abParamVal[8];
}

And it ^should^ allow you to cast the byte array to the structure.

Hope this helps.
 

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