473,396 Members | 1,982 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,396 software developers and data experts.

Marshal.SizeOf

Given:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
private struct PROCESSENTRY32
{
public int dwSize;
public int cntUsage;
public int th32ProcessID;
public int th32DefaultHeapID;
public int th32ModuleID;
public int cntThreads;
public int th32ParentProcessID;
public int pcPriClassBase;
public int dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAX_PATH)]
public char szExeFile;
}

and

PROCESSENTRY32 pe32 = new PROCESSENTRY32();

I was using the following:

pe32.dwSize =sizeof(PROCESSENTRY32);

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\EnumProcesses\Code-GetUsageCount\CsharpGetUsageCount\Form1.cs(340):
'CsharpGetUsageCount.Form1.MODULEENTRY32' 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 6656
Hi,
[Inline]

"Howard Kaikow" <ka****@standards.com> wrote in message
news:eQ**************@TK2MSFTNGP10.phx.gbl...
Given:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
private struct PROCESSENTRY32
{
public int dwSize;
public int cntUsage;
public int th32ProcessID;
public int th32DefaultHeapID;
public int th32ModuleID;
public int cntThreads;
public int th32ParentProcessID;
public int pcPriClassBase;
public int dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAX_PATH)]
public char szExeFile;
}
The last part should be:
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAX_PATH)]
public string szExeFile;


and

PROCESSENTRY32 pe32 = new PROCESSENTRY32();

I was using the following:

pe32.dwSize =sizeof(PROCESSENTRY32);
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(PROCESSENTRY32));

Which results in the following error at build time:

D:\Visual Basic
Code\API\EnumProcesses\Code-GetUsageCount\CsharpGetUsageCount\Form1.cs(340):
'CsharpGetUsageCount.Form1.MODULEENTRY32' 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**************@tk2msftngp13.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("kernel32", EntryPoint="Process32First", ExactSpelling=false,
CharSet=CharSet.Ansi, SetLastError=true)]
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.zip

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

"Howard Kaikow" <ka****@standards.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
"Bart Mermuys" <bm*************@hotmail.com> wrote in message
news:uf**************@tk2msftngp13.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("kernel32", EntryPoint="Process32First", ExactSpelling=false,
CharSet=CharSet.Ansi, SetLastError=true)]
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("kernel32", CharSet=CharSet.Auto, SetLastError=true)]
private static extern bool Process32First(IntPtr hSnapshot, ref
PROCESSENTRY32 lppe);
Example:

[StructLayout(LayoutKind.Sequential)]
struct PROCESSENTRY32
{
public int dwSize;
public int cntUsage;
public int th32ProcessID;
public int th32DefaultHeapID;
public int th32ModuleID;
public int cntThreads;
public int th32ParentProcessID;
public int pcPriClassBase;
public int dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]
public string szExeFile;
}

const uint TH32CS_SNAPPROCESS = 0x00000002;

[DllImport("kernel32.dll",SetLastError=true)]
public static extern IntPtr CreateToolhelp32Snapshot(
uint dwFlags,
uint th32ProcessID );

[DllImport("kernel32.dll",SetLastError=true)]
public static extern bool Process32First(
IntPtr hSnapshot,
ref PROCESSENTRY32 lppe );

[DllImport("kernel32.dll",SetLastError=true)]
public static extern bool Process32Next(
IntPtr hSnapshot,
ref PROCESSENTRY32 lppe );

[DllImport("kernel32.dll",SetLastError=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 = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );

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

while ( ret )
{
// show current
Console.WriteLine( pe.szExeFile + "\t" + pe.th32ProcessID + "\t" +
pe.cntThreads );

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

CloseHandle(p);
Console.ReadLine();
}

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.zip

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****@standards.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
"Bart Mermuys" <bm*************@hotmail.com> wrote in message
news:uf**************@tk2msftngp13.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("kernel32", EntryPoint="Process32First", ExactSpelling=false,
CharSet=CharSet.Ansi, SetLastError=true)]
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.zip

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.Diagnostics and System.Management 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**************@tk2msftngp13.phx.gbl...
Why convert and not simply use what's offered by the FCL, especially the
System.Diagnostics and System.Management 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
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...
2
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...
6
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...
1
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?...
4
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
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 =...
2
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
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...
1
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....
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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...
0
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...

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.