473,748 Members | 5,849 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

trying to port some C++ structures to C# problem.

I am trying to port some C++ structures to C# but I have troubles with this
one.
Note: this is a file record, so I must keep this format.

#pragma pack( push, 1 )
typedef struct {
char title[80];

DWORD dwCount;
} STLHEADER, *LPSTLHEADER;
#pragma pack( pop )

Using Google I discovered that this could be ported to this C# variant,
note the 'Marshal' to create a 80 byte array.

[StructLayout(La youtKind.Sequen tial, Pack=1)]
internal struct STLHEADER {
[MarshalAs (UnmanagedType. U1, SizeConst=80)]
public char[] title;

public int dwCount;
}

So far so good, but now I am stuck on this line "sizeof(STLHEAD ER)" needed
in a unsafe function.
error CS0208: Cannot take the address or size of a variable of a managed
type ('MySpace.STLHE ADER')

And it has something to do with the Marshal thing.
I could replace the "sizeof(STLHEAD ER)" with 80+4 but I would really prefer
to have a more professional sollution.
Maybe there is another alternative way to define a 'char title[80]' byte
array?

Thanks for any feedback. :-)

--
http://www.skyscan.be
Nov 16 '05 #1
26 4831
Since you struct is using reference types(char []) you will need to use the
System.Runtime. InteropServices .Marshal.SizeOf method to determine the size
of your structure.

One more thing; you should change the char [] member into a byte [].
Otherwise, your data will not be parsed correctly, since char [80] in C# is
actually
160 bytes of size.
byte [] is in C# what char [] was in C++.
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:41******** **************@ news.skynet.be. ..
I am trying to port some C++ structures to C# but I have troubles with this
one.
Note: this is a file record, so I must keep this format.

#pragma pack( push, 1 )
typedef struct {
char title[80];

DWORD dwCount;
} STLHEADER, *LPSTLHEADER;
#pragma pack( pop )

Using Google I discovered that this could be ported to this C# variant,
note the 'Marshal' to create a 80 byte array.

[StructLayout(La youtKind.Sequen tial, Pack=1)]
internal struct STLHEADER {
[MarshalAs (UnmanagedType. U1, SizeConst=80)]
public char[] title;

public int dwCount;
}

So far so good, but now I am stuck on this line "sizeof(STLHEAD ER)"
needed
in a unsafe function.
error CS0208: Cannot take the address or size of a variable of a managed
type ('MySpace.STLHE ADER')

And it has something to do with the Marshal thing.
I could replace the "sizeof(STLHEAD ER)" with 80+4 but I would really
prefer
to have a more professional sollution.
Maybe there is another alternative way to define a 'char title[80]' byte
array?

Thanks for any feedback. :-)

--
http://www.skyscan.be

Nov 16 '05 #2
And;
change
[MarshalAs (UnmanagedType. U1, SizeConst=80)]
into
[MarshalAs (UnmanagedType. ByValArray, SizeConst=80)]

So, now we have got:
[StructLayout(La youtKind.Sequen tial, Pack = 1)]
internal struct STLHEADER
{
[MarshalAs (UnmanagedType. ByValArray, SizeConst = 80)]
public byte [] title;
public int dwCount;
}
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Dennis Myrén" <de****@oslokb. no> wrote in message
news:2n******** ************@ne ws4.e.nsc.no...
Since you struct is using reference types(char []) you will need to use
the
System.Runtime. InteropServices .Marshal.SizeOf method to determine the size
of your structure.

One more thing; you should change the char [] member into a byte [].
Otherwise, your data will not be parsed correctly, since char [80] in C#
is actually
160 bytes of size.
byte [] is in C# what char [] was in C++.
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:41******** **************@ news.skynet.be. ..
I am trying to port some C++ structures to C# but I have troubles with
this
one.
Note: this is a file record, so I must keep this format.

#pragma pack( push, 1 )
typedef struct {
char title[80];

DWORD dwCount;
} STLHEADER, *LPSTLHEADER;
#pragma pack( pop )

Using Google I discovered that this could be ported to this C# variant,
note the 'Marshal' to create a 80 byte array.

[StructLayout(La youtKind.Sequen tial, Pack=1)]
internal struct STLHEADER {
[MarshalAs (UnmanagedType. U1, SizeConst=80)]
public char[] title;

public int dwCount;
}

So far so good, but now I am stuck on this line "sizeof(STLHEAD ER)"
needed
in a unsafe function.
error CS0208: Cannot take the address or size of a variable of a managed
type ('MySpace.STLHE ADER')

And it has something to do with the Marshal thing.
I could replace the "sizeof(STLHEAD ER)" with 80+4 but I would really
prefer
to have a more professional sollution.
Maybe there is another alternative way to define a 'char title[80]' byte
array?

Thanks for any feedback. :-)

--
http://www.skyscan.be


Nov 16 '05 #3
Not sure why you need this size for, but you have to:
- Declare the array element as UnmanagedType.B yValArray, and
- use the Marshal.SizeOf method to get the marshaled size of a struct.

[StructLayout(La youtKind.Sequen tial, Pack=1)]
internal struct STLHEADER {
[MarshalAs (UnmanagedType. ByValArray, SizeConst=80)]
public char[] title;
public int dwCount;
}

....
STLHEADER stlh = new STLHEADER();
int marshaledSizeOf Struct = Marshal.SizeOf( stlh); // should be 84

Willy.
"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:41******** **************@ news.skynet.be. ..
I am trying to port some C++ structures to C# but I have troubles with this
one.
Note: this is a file record, so I must keep this format.

#pragma pack( push, 1 )
typedef struct {
char title[80];

DWORD dwCount;
} STLHEADER, *LPSTLHEADER;
#pragma pack( pop )

Using Google I discovered that this could be ported to this C# variant,
note the 'Marshal' to create a 80 byte array.

[StructLayout(La youtKind.Sequen tial, Pack=1)]
internal struct STLHEADER {
[MarshalAs (UnmanagedType. U1, SizeConst=80)]
public char[] title;

public int dwCount;
}

So far so good, but now I am stuck on this line "sizeof(STLHEAD ER)"
needed
in a unsafe function.
error CS0208: Cannot take the address or size of a variable of a managed
type ('MySpace.STLHE ADER')

And it has something to do with the Marshal thing.
I could replace the "sizeof(STLHEAD ER)" with 80+4 but I would really
prefer
to have a more professional sollution.
Maybe there is another alternative way to define a 'char title[80]' byte
array?

Thanks for any feedback. :-)

--
http://www.skyscan.be

Nov 16 '05 #4
Wow thanks for the quick responce.

But Now I get this problem:

int iSTLHeaderSize= Marshal.SizeOf( STLHEADER);
Generates an error error "CS0118: 'MySpace.STLHEA DER' denotes a 'class'
where a 'variable' was expected"
Odd since STLHEADER) is a structure type.

Another problem is this;

Normally without the char[] the code works fine

fixed (void *lSTLHeader=&ST LFile.BufferPtr[0]) {
STLHEADER *pSTLHeader=(ST LHEADER *)lSTLHeader;
....
}

But because of the Marshal thing, it refuses to work so I found a tip to
use 'Marshal.PtrToS tructure' on Google.
So I tried this:
fixed (void *lSTLHeader=&ST LFile.BufferPtr[0]) {
STLHEADER *pSTLHeader= (STLHEADER *)
Marshal.PtrToSt ructure(lSTLHea der,typeof(STLH EADER) );
}

But 'Marshal.PtrToS tructure' tells me now that lSTLHeader should be a
IntPtr, so now is the question how can I convert void *lSTLHeader to
IntPtr????

(As you can see I am very new to this Marshal thing)
I appreciate the help though. :-)
--
http://www.skyscan.be
Nov 16 '05 #5
The SizeOf method has two overloads, one expecting a type, the other
expecting an instance of a type. I think the most efficient one would be
that one taking a type, so to get the size, do:
int size = Marshal.SizeOf( typeof(STLHEADE R));

Olaf Baeyens <ol**********@s kyscan.be> wrote:
But because of the Marshal thing, it refuses to work so I found a tip to
use 'Marshal.PtrToS tructure' on Google.
So I tried this:
fixed (void *lSTLHeader=&ST LFile.BufferPtr[0]) {
STLHEADER *pSTLHeader= (STLHEADER *)
Marshal.PtrToS tructure(lSTLHe ader,typeof(STL HEADER) );
} If your structure did not use reference types(byte []), you could have done:
byte [] buff = new byte [sizeof(STLHEADE R)];
[LOAD RAW DATA INTO buff]
fixed (byte * pBuff = buff)
header = * ((STLHEADER *) pBuff);

However, since you use a reference type in the structure, i think this is
the way to do it:
byte [] buff = new byte [Marshal.SizeOf( typeof(STLHEADE R))];
[LOAD RAW DATA INTO buff]
IntPtr ptr = Marshal.AllocHG lobal(buff.Leng th);
Marshal.Copy(bu ff, 0x0, ptr, buff.Length);
header = (STLHEADER) Marshal.PtrToSt ructure(ptr, typeof(STLHEADE R));
Marshal.FreeHGl obal(ptr);

HTH.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:41******** *************** @news.skynet.be ... Wow thanks for the quick responce.

But Now I get this problem:

int iSTLHeaderSize= Marshal.SizeOf( STLHEADER);
Generates an error error "CS0118: 'MySpace.STLHEA DER' denotes a 'class'
where a 'variable' was expected"
Odd since STLHEADER) is a structure type.

Another problem is this;

Normally without the char[] the code works fine

fixed (void *lSTLHeader=&ST LFile.BufferPtr[0]) {
STLHEADER *pSTLHeader=(ST LHEADER *)lSTLHeader;
....
}

But because of the Marshal thing, it refuses to work so I found a tip to
use 'Marshal.PtrToS tructure' on Google.
So I tried this:
fixed (void *lSTLHeader=&ST LFile.BufferPtr[0]) {
STLHEADER *pSTLHeader= (STLHEADER *)
Marshal.PtrToSt ructure(lSTLHea der,typeof(STLH EADER) );
}

But 'Marshal.PtrToS tructure' tells me now that lSTLHeader should be a
IntPtr, so now is the question how can I convert void *lSTLHeader to
IntPtr????

(As you can see I am very new to this Marshal thing)
I appreciate the help though. :-)
--
http://www.skyscan.be

Nov 16 '05 #6
> int size = Marshal.SizeOf( typeof(STLHEADE R));

This worked! typeof was missing. :-)

The rest I am trying to implement now, I report back if it works.

But I am wondering, since I use pure C# why do I need marshalling at all?
The structure is created in C# and the parsing and loading functionality of
the binary file is also created in that same C# assembly.
So as far as I understand this, I do not have a situation between managed
and unmnaged code because it is pure C#.

There is probably a very logical reason for this. :-)

--
http://www.skyscan.be
Nov 16 '05 #7
See inline ****
Willy.
"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:41******** *************** @news.skynet.be ...
Wow thanks for the quick responce.

But Now I get this problem:

int iSTLHeaderSize= Marshal.SizeOf( STLHEADER);
Generates an error error "CS0118: 'MySpace.STLHEA DER' denotes a 'class'
where a 'variable' was expected"
Odd since STLHEADER) is a structure type.
*** There's is nothin odd, SizeOf takes a variable argument like:
STLHEADER stlh = new STLHEADER();
int iSTLHeaderSize= Marshal.SizeOf( stlh);

or:
int iSTLHeaderSize= Marshal.SizeOf( typeof(STLHEADE R));

Another problem is this;

Normally without the char[] the code works fine

fixed (void *lSTLHeader=&ST LFile.BufferPtr[0]) {
STLHEADER *pSTLHeader=(ST LHEADER *)lSTLHeader;
....
}

But because of the Marshal thing, it refuses to work so I found a tip to
use 'Marshal.PtrToS tructure' on Google.
So I tried this:
fixed (void *lSTLHeader=&ST LFile.BufferPtr[0]) {
STLHEADER *pSTLHeader= (STLHEADER *)
Marshal.PtrToSt ructure(lSTLHea der,typeof(STLH EADER) );
}

But 'Marshal.PtrToS tructure' tells me now that lSTLHeader should be a
IntPtr, so now is the question how can I convert void *lSTLHeader to
IntPtr????

(As you can see I am very new to this Marshal thing)
I appreciate the help though. :-)


What you need is StructureToPtr, that is marshal a structure to a
pointer....

STLHEADER stlh = new STLHEADER(); // crate instance of struct
.... // initialize the struct fields
int iSTLHeaderSize= Marshal.SizeOf( stlh); // get size of marshaled struct
IntPtr stlhPtr = Marshal.AllocHG lobal( iSTLHeaderSize) // allocate
unmanaged memory with size of struct
Marshal.Structu reToPtr(stlh , stlhPtr , true); // mashal managed
struct to unmanaged struct
.....// use unmanaged struct pointer to call unmanaged code functions
.....
Marshal.FreeHGl obal(stlhPtr ); // Free unmanaged memory when done

But again I'm not sure this is what you want, therefore I asked why you
needed the size of the struct.

Willy.

Nov 16 '05 #8
Well, you could have avoided using Marshal utilities by manually loading the
members of STLHEADER
from a raw byte array source.

Marshalling could also have been avoided if the structure contained only
value types.
As the first example in my last post showed, you then could have used
"unsafe" code statements
in order to cast a raw byte array into a data structure.
This is possible since the structure is then stored in RAM in the exact way
as it was declared.
However, if reference types is used in the structure, you will need
something to marshal
them as if they were value types, because they are actually allocated on the
heap.

For instance, what i guess Marshal.SizeOf does, is locating any reference
types that are
members of the structure on the heap and measures it's size explicitly.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:41******** *************** @news.skynet.be ...
int size = Marshal.SizeOf( typeof(STLHEADE R));

This worked! typeof was missing. :-)

The rest I am trying to implement now, I report back if it works.

But I am wondering, since I use pure C# why do I need marshalling at all?
The structure is created in C# and the parsing and loading functionality
of
the binary file is also created in that same C# assembly.
So as far as I understand this, I do not have a situation between managed
and unmnaged code because it is pure C#.

There is probably a very logical reason for this. :-)

--
http://www.skyscan.be

Nov 16 '05 #9
> But again I'm not sure this is what you want, therefore I asked why you
needed the size of the struct.

Wel I have a binary STL file that contains a header and then a lot of 3D
triangles.
What I do is to load the complete file in memory, then maps a structure to
the header and if that structure is correct then I map another STLFACET
structure for every triangle.

It is code that is needed for my OpenGL visualization stuff, and since the
original data files can be huge, I try to avoid copying as much as I can.
Managed code is perfect for 3D modelling stuff. No more tracking of who
created the object and who should delete it. Wonderfull. :-)

This STL parser is only the beginning part, I try to create the technology
to parse any potentional binary file formats (bmp, tiff, jpg,...) that I
might encounter.
I want to create a code base for this.

--
http://www.skyscan.be
Nov 16 '05 #10

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

Similar topics

12
2847
by: Don Bruder | last post by:
A week or two ago, I asked here about porting Python to C. Got some good answers (Note 1) but now I've got another question. Actually, more a request for clarification of a topic that both the Python tutorial and docs leave a touch murky to my understanding. Dictionaries/"dict" types... Am I understanding/interpreting correctly when I go with the idea that a "dict" variable can be looked at as (effectively) two parallel arrays?...
5
3893
by: The Beast | last post by:
I'm trying to create a thread to write to the serial port and I keep getting an odd error cannot convert parameter 3 from 'unsigned long (void *)' to 'unsigned long (__stdcall *)(void *)' and it points to the CreateThread call. Here is my class, why is it doing this and how can I fix it? <TxdRxd.h>
4
3862
by: Thomas Paul Diffenbach | last post by:
Can anyone point me to an open source library of /statically allocated/ data structures? I'm writing some code that would benefit from trees, preferably self balancing, but on an embedded system that doesn't offer dynamic memory allocation (to be clear: no malloc, no realloc), and with rather tight memory constraints. Writing my own malloc to do dynamic allocation from some static pool isn't really an option, for various reasons, not...
4
2240
by: Deniz Bahar | last post by:
Hello, A couple days ago my friend (OOP guy) shows me what OOP was all about in C++. This morning I figured I can do pretty much the same thing with C (by putting function pointers in structures and using Macros). I've gone pretty far but I'm running into problems because the function pointers within the structures need an extra argument (a pointer to that type of structure) so they know which data to operate on. Also, I have to...
13
4047
by: PengYu.UT | last post by:
Hi, I have to use some machine with only support of C. But I have some C++ programs, which use most C++ comman features. Is there any way to convert those C++ programs to C? Or is there any way that I can mimic C++ by C? So that even if I have to recode, I don't have to change the C++ code structures. Thanks!
13
4832
by: Al the programmer | last post by:
I need to access the serial ports on my webserver from an asp.net page. I have no problem accessing the serial ports from a windows form application, but the code doesn't work in asp.net. I have been told it is not possible to access the serial ports from asp.net. The application is used to control custom hardware. The hardware is connected to a PC through serial ports. Our customer wants to control the hardware from a remote...
2
2412
by: py | last post by:
Is there a way in python to figure out which process is running on which port? I know in Windows XP you can run "netstat -o" and see the process ID for each open port....but I am looking for something not tied to windows particularly, hopefully something in python. if not, any known way, such as netstat shown above, for other versions of windows (such as 98, 2000) and even linux? thanks
4
3338
by: farc | last post by:
I am in the process of converting an old C application to C#. The application is loaded with pointers (as most are, I guess). How would I best represent the following structures in C#? typedef char ** mytypedef; typedef struct _mystructure { struct _mystructure *left, *right; } mystructure;
1
2736
by: danfolkes | last post by:
Hey Everyone, I am trying to send repeated messages from a "Node" to a "Server". It works the first time I send the from the Node to Server, but after that it either errors, or does not do anything. I would love some help, here is the code: import socket import thread import time
0
8984
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
8823
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9530
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9312
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,...
1
6793
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
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4593
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
4864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3300
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

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.