473,387 Members | 3,820 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Cannot take the address or size of managed type

Hello everyone

I have been trying to read and write struct to binary
files, I'm using
to functions to convert the struct to bytes and bytes to
struct, I
always receive the following error

C:\Documents and Settings\jon.JONHS-LAP\My
Documents\Visual Studio
Projects\StructTest\Class1.cs(100): Cannot take the
address or size of
a variable of a managed type ('StructTest.test')

Here is my code, what is I doing wrong here.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
namespace StructTest
{

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct test
{
[MarshalAs(UnmanagedType.I4, SizeConst=3)]
public int[] local;
public int local1;
public int local2;
}
class Class1
{

[STAThread]
static unsafe void Main(string[] args)
{

int[] y = new int[3];

y.SetValue(12,0);
y.SetValue(12,1);
y.SetValue(12,2);

test h = new test();
h.local = y;
h.local1 = 20;
h.local2 = 30;

FileStream fs = new FileStream
("Test5.txt",FileMode.Open);

int tr = Marshal.SizeOf(h);

byte[] array = new byte[tr];

array = YourStructToBytes(h);

test g = new test();

g = BytesToYourStruct(array);

fs.Read(array,0,tr);

}
static unsafe byte[] YourStructToBytes( test s )
{
byte[] arr = new byte[ Marshal.SizeOf(s) ];
fixed( byte* parr = arr )
{
*((test*)parr) = s;//Cannot take the address
or size of a
variable of a managed type
}
return arr;
}

static unsafe test BytesToYourStruct( byte[] arr )
{
if( arr.Length < sizeof(test) )
throw new ArgumentException();

test s;
fixed( byte* parr = arr )
{ s = *((test*)parr); }
return s;
}
}
}

Nov 15 '05 #1
1 7983
Hi,

1) If you want to do this with Interop & Marshal, you must create a
unmanaged buffer

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct test
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=3)]
public int[] local0;
public int local1;
public int local2;
}

static byte[] YourStructToBytes( test s )
{
int size = Marshal.SizeOf( s );
byte[] retArr = new byte[ size ];
IntPtr buf = Marshal.AllocHGlobal( size ); // create unmanaged memory
Marshal.StructureToPtr ( s, buf, false ); // copy struct

for (int i=0; i<size; ++i)
{
retArr[i] = Marshal.ReadByte(buf, i); // read unmanaged bytes
}
Marshal.FreeHGlobal( buf );
return retArr;
}

static test YourBytesToStruct( byte[] arr )
{
test retVal = new test();
int size = Marshal.SizeOf(retVal);
//if ( arr.Length < size ) // Throw
IntPtr buf = Marshal.AllocHGlobal( size );
for (int i=0; i<size; ++i)
{
Marshal.WriteByte(buf, i, arr[i]);
}

retVal = (test) Marshal.PtrToStructure( buf, typeof(test) );
Marshal.FreeHGlobal( buf );
return retVal;
}

public void Test()
{
test a;
a.local0 = new int[] { 10,10,10 };
a.local1 = 10;
a.local2 = 20;

// copy "a" to "b"
byte[] bytes = YourStructToBytes(a);
test b = YourBytesToStruct(bytes);
Console.WriteLine ("{0} {1}", b.local1, b.local2);
}

2) Use Serialization with Reflection and a MemoryStream
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public struct test
{
public int[] local0;
public int local1;
public int local2;
}

private byte[] YourStructToBytes2(test s)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize (ms, s);
return ms.GetBuffer();
}

private test YourBytesToStruct2( byte[] b)
{
MemoryStream ms = new MemoryStream( b );
BinaryFormatter bf = new BinaryFormatter();
return (test) bf.Deserialize (ms);
}

public void Test2()
{
// create "a"
test a;
a.local0 = new int[] { 10,10,10 };
a.local1 = 10;
a.local2 = 20;

// copy "a" to "b"
byte[] bytes = YourStructToBytes2(a);
test b = YourBytesToStruct2( bytes2 );
Console.WriteLine ("{0} {1}", b.local1, b.local2);
}
HTH,
Greetings

"Jón Sveinsson" <ru******@hotmail.com> wrote in message
news:9b****************************@phx.gbl...
Hello everyone

I have been trying to read and write struct to binary
files, I'm using
to functions to convert the struct to bytes and bytes to
struct, I
always receive the following error

C:\Documents and Settings\jon.JONHS-LAP\My
Documents\Visual Studio
Projects\StructTest\Class1.cs(100): Cannot take the
address or size of
a variable of a managed type ('StructTest.test')

Here is my code, what is I doing wrong here.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
namespace StructTest
{

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct test
{
[MarshalAs(UnmanagedType.I4, SizeConst=3)]
public int[] local;
public int local1;
public int local2;
}
class Class1
{

[STAThread]
static unsafe void Main(string[] args)
{

int[] y = new int[3];

y.SetValue(12,0);
y.SetValue(12,1);
y.SetValue(12,2);

test h = new test();
h.local = y;
h.local1 = 20;
h.local2 = 30;

FileStream fs = new FileStream
("Test5.txt",FileMode.Open);

int tr = Marshal.SizeOf(h);

byte[] array = new byte[tr];

array = YourStructToBytes(h);

test g = new test();

g = BytesToYourStruct(array);

fs.Read(array,0,tr);

}
static unsafe byte[] YourStructToBytes( test s )
{
byte[] arr = new byte[ Marshal.SizeOf(s) ];
fixed( byte* parr = arr )
{
*((test*)parr) = s;//Cannot take the address
or size of a
variable of a managed type
}
return arr;
}

static unsafe test BytesToYourStruct( byte[] arr )
{
if( arr.Length < sizeof(test) )
throw new ArgumentException();

test s;
fixed( byte* parr = arr )
{ s = *((test*)parr); }
return s;
}
}
}

Nov 15 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: baustin75 | last post by:
Posted: Mon Oct 03, 2005 1:41 pm Post subject: cannot mail() in ie only when debugging in php designer 2005 -------------------------------------------------------------------------------- ...
22
by: Smutny30 | last post by:
Hello, I am preparing a database that will store 10 n * GBs - 100 n * GBs of data. I calculated to have 1,2 GB of bufferpools. I run the DB2 v. 8.2.1 alone on 4 GB box. I obtain : ...
2
by: Jack | last post by:
Anybody know how to determine the "sizeof" a class? TYIA Jack jackmcgillis@netscape.NOSPAM.net
0
by: J?n Sveinsson | last post by:
Hello everyone I have been trying to read and write struct to binary files, I'm using to functions to convert the struct to bytes and bytes to struct, I always receive the following error ...
7
by: Lei Jiang | last post by:
I'd like to calculate the memory size that my data structure cost, but I could not find any API that I could calculate the size of an object. Could anyone give me a work around? Thanks!
3
by: anuragpj | last post by:
i have designed a login page like this: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Electrical Engineering Dept...
0
by: jianxin9 | last post by:
Hi everyone, I don't have a lot of experience with ASP and I was hoping someone could help me. I want to use our ASP form along with some javascript code to create a form where our patrons can...
21
by: Mick1000 | last post by:
Hi all, I am new to perl and this forum. I am trying to setup a mailing list subscription functionality for customers to receive a periodic newsletter from me. My perl program grabs the html form...
3
by: pinko1204 | last post by:
My Update function cannot successful update to sql table even don't have any error. Please help to check .....thx PHP1 <?php require_once 'header.php'; ?> <style type="text/css"> <!--
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.