473,795 Members | 2,498 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.JO NHS-LAP\My
Documents\Visua l Studio
Projects\Struct Test\Class1.cs( 100): Cannot take the
address or size of
a variable of a managed type ('StructTest.te st')

Here is my code, what is I doing wrong here.
using System;
using System.IO;
using System.Runtime. Serialization.F ormatters.Binar y;
using System.Runtime. InteropServices ;
namespace StructTest
{

[StructLayout(La youtKind.Sequen tial, Pack=1)]
public struct test
{
[MarshalAs(Unman agedType.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",Fi leMode.Open);

int tr = Marshal.SizeOf( h);

byte[] array = new byte[tr];

array = YourStructToByt es(h);

test g = new test();

g = BytesToYourStru ct(array);

fs.Read(array,0 ,tr);

}
static unsafe byte[] YourStructToByt es( 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 BytesToYourStru ct( byte[] arr )
{
if( arr.Length < sizeof(test) )
throw new ArgumentExcepti on();

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

Nov 15 '05 #1
1 8006
Hi,

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

[StructLayout(La youtKind.Sequen tial, Pack=1)]
public struct test
{
[MarshalAs(Unman agedType.ByValA rray, SizeConst=3)]
public int[] local0;
public int local1;
public int local2;
}

static byte[] YourStructToByt es( test s )
{
int size = Marshal.SizeOf( s );
byte[] retArr = new byte[ size ];
IntPtr buf = Marshal.AllocHG lobal( size ); // create unmanaged memory
Marshal.Structu reToPtr ( s, buf, false ); // copy struct

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

static test YourBytesToStru ct( byte[] arr )
{
test retVal = new test();
int size = Marshal.SizeOf( retVal);
//if ( arr.Length < size ) // Throw
IntPtr buf = Marshal.AllocHG lobal( size );
for (int i=0; i<size; ++i)
{
Marshal.WriteBy te(buf, i, arr[i]);
}

retVal = (test) Marshal.PtrToSt ructure( buf, typeof(test) );
Marshal.FreeHGl obal( 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 = YourStructToByt es(a);
test b = YourBytesToStru ct(bytes);
Console.WriteLi ne ("{0} {1}", b.local1, b.local2);
}

2) Use Serialization with Reflection and a MemoryStream
using System.Runtime. Serialization.F ormatters.Binar y;

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

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

private test YourBytesToStru ct2( 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 = YourStructToByt es2(a);
test b = YourBytesToStru ct2( bytes2 );
Console.WriteLi ne ("{0} {1}", b.local1, b.local2);
}
HTH,
Greetings

"Jón Sveinsson" <ru******@hotma il.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.JO NHS-LAP\My
Documents\Visua l Studio
Projects\Struct Test\Class1.cs( 100): Cannot take the
address or size of
a variable of a managed type ('StructTest.te st')

Here is my code, what is I doing wrong here.
using System;
using System.IO;
using System.Runtime. Serialization.F ormatters.Binar y;
using System.Runtime. InteropServices ;
namespace StructTest
{

[StructLayout(La youtKind.Sequen tial, Pack=1)]
public struct test
{
[MarshalAs(Unman agedType.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",Fi leMode.Open);

int tr = Marshal.SizeOf( h);

byte[] array = new byte[tr];

array = YourStructToByt es(h);

test g = new test();

g = BytesToYourStru ct(array);

fs.Read(array,0 ,tr);

}
static unsafe byte[] YourStructToByt es( 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 BytesToYourStru ct( byte[] arr )
{
if( arr.Length < sizeof(test) )
throw new ArgumentExcepti on();

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
5483
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 -------------------------------------------------------------------------------- Hello, I have a very simple problem but cannot seem to figure it out. I have a very simple php script that sends a test email to myself. When I debug it in PHP designer, it works with no problems, I get the test email. If
22
5596
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 : "SQL1478W The defined buffer pools could not be started. Instead, one small
2
4130
by: Jack | last post by:
Anybody know how to determine the "sizeof" a class? TYIA Jack jackmcgillis@netscape.NOSPAM.net
0
2093
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 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')
7
3252
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
1668
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 IITK</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!--
0
2181
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 select which department they will send the form to (we are trying to consolidate forms). This is what I have so far, but when I test the form, I keep getting this error message: Mailing Failed... Error is: FromAddress Property cannot be blank. You...
21
5823
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 'email address' text input but I am then having issues writing this data to a plain text file. Below is my html form followed by my perl script. When i run this on IIS, i dont receive any errors, nor does anything get written to the file. Any help...
3
2322
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
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10213
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10163
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9040
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.