473,545 Members | 721 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Marshal.SizeOf

Given:

[StructLayout(La youtKind.Sequen tial, CharSet=CharSet .Auto)]
private struct PROCESSENTRY32
{
public int dwSize;
public int cntUsage;
public int th32ProcessID;
public int th32DefaultHeap ID;
public int th32ModuleID;
public int cntThreads;
public int th32ParentProce ssID;
public int pcPriClassBase;
public int dwFlags;
[MarshalAs(Unman agedType.ByValT Str, SizeConst=MAX_P ATH)]
public char szExeFile;
}

and

PROCESSENTRY32 pe32 = new PROCESSENTRY32( );

I was using the following:

pe32.dwSize =sizeof(PROCESS ENTRY32);

But that returned the wrong value 40 instead of the correct value 296, as
MAX_PATH is 260.

So I tried the following:

pe32.dwSize = Marshal.SizeOf( PROCESSENTRY32) ;

Which results in the following error at build time:

D:\Visual Basic
Code\API\EnumPr ocesses\Code-GetUsageCount\C sharpGetUsageCo unt\Form1.cs(34 0):
'CsharpGetUsage Count.Form1.MOD ULEENTRY32' denotes a 'class' where a
'variable' was expected

So, I tried

pe32.dwSize = Marshal.SizeOf( pe32);

Alas, that ended up causing an exception, with the message:

"Type PROCESSENTRY32 can not be marshaled as an unmanaged structure; no
meaningful size or offset can be computed."

What do I need to do to correct the problem?
Nov 17 '05 #1
6 6676
Hi,
[Inline]

"Howard Kaikow" <ka****@standar ds.com> wrote in message
news:eQ******** ******@TK2MSFTN GP10.phx.gbl...
Given:

[StructLayout(La youtKind.Sequen tial, CharSet=CharSet .Auto)]
private struct PROCESSENTRY32
{
public int dwSize;
public int cntUsage;
public int th32ProcessID;
public int th32DefaultHeap ID;
public int th32ModuleID;
public int cntThreads;
public int th32ParentProce ssID;
public int pcPriClassBase;
public int dwFlags;
[MarshalAs(Unman agedType.ByValT Str, SizeConst=MAX_P ATH)]
public char szExeFile;
}
The last part should be:
[MarshalAs(Unman agedType.ByValT Str, SizeConst=MAX_P ATH)]
public string szExeFile;


and

PROCESSENTRY32 pe32 = new PROCESSENTRY32( );

I was using the following:

pe32.dwSize =sizeof(PROCESS ENTRY32);
use Marshal.SizeOf

But that returned the wrong value 40 instead of the correct value 296, as
MAX_PATH is 260.
Yeah, but since you chosen Auto for charset, strings will be wide on nt
versions of windows. So the struct would be at least 260*2, this doesn't
have to be a problem though.

So I tried the following:

pe32.dwSize = Marshal.SizeOf( PROCESSENTRY32) ;
Should be :
pe32.dwSize = Marshal.SizeOf( typeof(PROCESSE NTRY32));

Which results in the following error at build time:

D:\Visual Basic
Code\API\EnumPr ocesses\Code-GetUsageCount\C sharpGetUsageCo unt\Form1.cs(34 0):
'CsharpGetUsage Count.Form1.MOD ULEENTRY32' denotes a 'class' where a
'variable' was expected

So, I tried

pe32.dwSize = Marshal.SizeOf( pe32);
That should work now.

HTH,
greetings

Alas, that ended up causing an exception, with the message:

"Type PROCESSENTRY32 can not be marshaled as an unmanaged structure; no
meaningful size or offset can be computed."

What do I need to do to correct the problem?

Nov 17 '05 #2
"Bart Mermuys" <bm************ *@hotmail.com> wrote in message
news:uf******** ******@tk2msftn gp13.phx.gbl...

Thanx.

Your suggestion worked.
Now the following

Process32First( hProcessSnap, pe32)

Results in the error

//Object reference not set to an instance of an object.

Where I have:

[DllImport("kern el32", EntryPoint="Pro cess32First", ExactSpelling=f alse,
CharSet=CharSet .Ansi, SetLastError=tr ue)]
private static extern bool Process32First( int hSnapshot, PROCESSENTRY32
lppe);

For your information, the goal is to convert the code at

http://msdn.microsoft.com/library/de..._processes.asp

I already have the code running in C++ .NET 2003

http://www.standards.com/OtherDownlo...s/UnmanagedC++
GetUsageCount.z ip

Goal is to get code working in C#, VB .NET and VB 6.
Nov 17 '05 #3
Hi,

"Howard Kaikow" <ka****@standar ds.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
"Bart Mermuys" <bm************ *@hotmail.com> wrote in message
news:uf******** ******@tk2msftn gp13.phx.gbl...

Thanx.

Your suggestion worked.
Now the following

Process32First( hProcessSnap, pe32)

Results in the error

//Object reference not set to an instance of an object.

Where I have:

[DllImport("kern el32", EntryPoint="Pro cess32First", ExactSpelling=f alse,
CharSet=CharSet .Ansi, SetLastError=tr ue)]
private static extern bool Process32First( int hSnapshot, PROCESSENTRY32
lppe);

- use IntPtr for C/C++ HANDLE types
- since you declared PROCESSENTRY32 as a _struct_ and you need to pass a
pointer, you have to use to ref keyword :
- use the same CharSet on both the structure and the api

[DllImport("kern el32", CharSet=CharSet .Auto, SetLastError=tr ue)]
private static extern bool Process32First( IntPtr hSnapshot, ref
PROCESSENTRY32 lppe);
Example:

[StructLayout(La youtKind.Sequen tial)]
struct PROCESSENTRY32
{
public int dwSize;
public int cntUsage;
public int th32ProcessID;
public int th32DefaultHeap ID;
public int th32ModuleID;
public int cntThreads;
public int th32ParentProce ssID;
public int pcPriClassBase;
public int dwFlags;
[MarshalAs(Unman agedType.ByValT Str, SizeConst=260)]
public string szExeFile;
}

const uint TH32CS_SNAPPROC ESS = 0x00000002;

[DllImport("kern el32.dll",SetLa stError=true)]
public static extern IntPtr CreateToolhelp3 2Snapshot(
uint dwFlags,
uint th32ProcessID );

[DllImport("kern el32.dll",SetLa stError=true)]
public static extern bool Process32First(
IntPtr hSnapshot,
ref PROCESSENTRY32 lppe );

[DllImport("kern el32.dll",SetLa stError=true)]
public static extern bool Process32Next(
IntPtr hSnapshot,
ref PROCESSENTRY32 lppe );

[DllImport("kern el32.dll",SetLa stError=true)]
public static extern bool CloseHandle(
IntPtr hObject // handle to object);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
IntPtr p = CreateToolhelp3 2Snapshot( TH32CS_SNAPPROC ESS, 0 );

PROCESSENTRY32 pe = new PROCESSENTRY32( );
pe.dwSize = Marshal.SizeOf( pe);
bool ret = Process32First( p, ref pe );

while ( ret )
{
// show current
Console.WriteLi ne( pe.szExeFile + "\t" + pe.th32ProcessI D + "\t" +
pe.cntThreads );

// get next
pe.dwSize = Marshal.SizeOf( pe);
ret = Process32Next( p, ref pe );
}

CloseHandle(p);
Console.ReadLin e();
}

HTH,
greetings

For your information, the goal is to convert the code at

http://msdn.microsoft.com/library/de..._processes.asp

I already have the code running in C++ .NET 2003

http://www.standards.com/OtherDownlo...s/UnmanagedC++
GetUsageCount.z ip

Goal is to get code working in C#, VB .NET and VB 6.

Nov 17 '05 #4
Thanx.

The problem appears to have been the missing ref.

Note that the code did not work when I used IntPtr.

What's the best book to address the type of questions I've asked?

Previously, I had only:

C# Essentials
A Progranmmer's Introduction to C#

This past week. I ordered:

The MSFT Press Step by Step book (received yesterday).
Liberty's Programming C#..
Hejlsberg's book.

Again, thanx, now it's on to do a VB .NET version.
That task should be easier since the issue of the ref has been solved.

At some point, I will be posting an article at my web site, goving the code
for the C++, C#, VB .NET and VB 6 versions, and describing whether the
intended problem has been solved, but I do not want to digress now.
Nov 17 '05 #5


"Howard Kaikow" <ka****@standar ds.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
"Bart Mermuys" <bm************ *@hotmail.com> wrote in message
news:uf******** ******@tk2msftn gp13.phx.gbl...

Thanx.

Your suggestion worked.
Now the following

Process32First( hProcessSnap, pe32)

Results in the error

//Object reference not set to an instance of an object.

Where I have:

[DllImport("kern el32", EntryPoint="Pro cess32First", ExactSpelling=f alse,
CharSet=CharSet .Ansi, SetLastError=tr ue)]
private static extern bool Process32First( int hSnapshot, PROCESSENTRY32
lppe);

For your information, the goal is to convert the code at

http://msdn.microsoft.com/library/de..._processes.asp

I already have the code running in C++ .NET 2003

http://www.standards.com/OtherDownlo...s/UnmanagedC++
GetUsageCount.z ip

Goal is to get code working in C#, VB .NET and VB 6.


Why convert and not simply use what's offered by the FCL, especially the
System.Diagnost ics and System.Manageme nt namespace classes are just what you
need to achieve what you are looking for.

If you have to PInvoke that much in C#, it means you didn't check the FCL
for a managed solution and you missed the point of .NET where the FCL is
key, not the language you use to implement, or you might have chosen the
wrong language.

Willy.

Nov 17 '05 #6
"Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
news:Or******** ******@tk2msftn gp13.phx.gbl...
Why convert and not simply use what's offered by the FCL, especially the
System.Diagnost ics and System.Manageme nt namespace classes are just what you need to achieve what you are looking for.

If you have to PInvoke that much in C#, it means you didn't check the FCL
for a managed solution and you missed the point of .NET where the FCL is
key, not the language you use to implement, or you might have chosen the
wrong language.


Yes, but the goal is to do the deed in VB 6.

I was having difficulty with the task in VB 6, so I decided to try running
the C code example at
http://msdn.microsoft.com/library/de..._processes.asp

I first put the code thru MSFT C++ V6 Learning edition.
Then I import that workspace into C++ .NET 2002, then into C++ .NET 2003.
Then to C#, and I just finished converting to VB .NET this evening.

I should be able to more easily implement a VB 6 version, using the VB .NET
version as a guide.

I do have a partial solution using the Framework stiff.
I found 11 of the 12 APIs I'm using are alleged to have Framework
equivalents.
Other is CloseHandle, have not yet looked for that equivalent.
Nov 17 '05 #7

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

Similar topics

4
3805
by: William Stacey | last post by:
Using the following struct def, how can I tell (using reflection) if "ba" has the marshal attribute and get the "ByValArray" and maybe even the size? In the bigger picture, given a struct (or a class), how to decide if "sizeof(MyStruct)" would fail before calling sizeof and having to use Marshal.sizeof? TIA public struct MyStruct {
2
9216
by: Beringer | last post by:
Why do I get the following run time error: Additional information: Type System.Object can not be marshaled as an unmanaged structure; no meaningful size or offset can be computed. When the following code is executed? object test = new object(); int temp = Marshal.SizeOf(test);
6
10802
by: SB | last post by:
I feel dumb to ask because I bet this is a simple question... Looking at the code below, can someone please explain why I get two different values in my Marshal.SizeOf calls (see the commented lines)? TIA! sb
1
4183
by: Claire | last post by:
char a = 'p'; if (System.Runtime.InteropServices.Marshal.SizeOf(a) == 1) dothis(); else dothat(); SizeOf(a) is returned as 1. I thought chars were 16 bits in size. Why is it returning 1 to me? thanks Claire
4
1547
by: marcosegurini | last post by:
Hi. Is is possible to mark a class-member-variable to avoid its marshaling? class MyClass { int i_; IntPtr point_;
2
8130
by: scottt | last post by:
I need to call into a C++ DLL from my C# code. The function is expecting a void pointer to an unsigned short. Which would be more correct? UInt16 wRegData; IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(wRegData)); Marshal.StructureToPtr(wRegData, p, false);
2
3175
by: RYoung | last post by:
Given this native struct: typedef struct vendor { char name; } VENDOR I want to make managed equivalent, so I did this: public value struct Vendor
0
2109
by: Charming12 | last post by:
Hi All, I have a strange problem and due to my inefficiency with IntPtr i am unable to figure it out. I have an structure something like: public struct Detail { public int age; public Detail(int _age)
1
2373
by: Charming12 | last post by:
Hi All, I am using System.Runtime.InteropServices; to marshal a structure using Marshal.structureToPtr(). But to get the size of structure when i get Marshal.sizeOf(), it gives me improper sizes. Code: public struct IDName { public ushort Id;
0
7465
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...
0
7656
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. ...
0
7752
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5969
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...
1
5325
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...
0
4944
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...
0
3449
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...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.