473,802 Members | 2,431 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Marshal.GetLast Win32Error()

Hi there,

Does anyone know if this (example) is safe:

[DllImport("user 32.dll", SetLastError = true)]
internal static extern int GetWindowRect(I ntPtr hWnd, ref RECT
rect);

int rc = GetWindowRect(h Wnd, ref rect);
if (rc == 0)
{
throw new Win32Exception( Marshal.GetLast Win32Error(), "Error");
}

My concern is the call to "Marshal.GetLas tWin32Error()". Can the value
returned by this function be modified by the call to the exception
constructor itself. For instance, could construction of the "Error" string
overwrite "Marshal.GetLas tWin32Error()" on failure given that it might also
call into the WinAPI. This would be a problem in C++ for instance where you
can't depend on the order of the parameters being passed (i.e., you can't
reliably pass "GetLastError() " as the first arg since the 2nd.arg might be
evaluated first - on failure it would then overwrite the first arg)
May 8 '07 #1
4 8832
Larry,

The only way that GetLastWin32Err or is going to return a different value
is if you use another call to unmanaged code. You should store the error if
you are going to perform an operation which could possibly change it, and
you need it for later.

I am curious, why are you passing an error string or the last error to
the Win32Exception class? If you use the default constructor, it should get
the value of the last win 32 error and also create the appropriate exception
message.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Larry Smith" <no_spam@_nospa m.comwrote in message
news:eJ******** ******@TK2MSFTN GP02.phx.gbl...
Hi there,

Does anyone know if this (example) is safe:

[DllImport("user 32.dll", SetLastError = true)]
internal static extern int GetWindowRect(I ntPtr hWnd, ref RECT
rect);

int rc = GetWindowRect(h Wnd, ref rect);
if (rc == 0)
{
throw new Win32Exception( Marshal.GetLast Win32Error(), "Error");
}

My concern is the call to "Marshal.GetLas tWin32Error()". Can the value
returned by this function be modified by the call to the exception
constructor itself. For instance, could construction of the "Error" string
overwrite "Marshal.GetLas tWin32Error()" on failure given that it might
also call into the WinAPI. This would be a problem in C++ for instance
where you can't depend on the order of the parameters being passed (i.e.,
you can't reliably pass "GetLastError() " as the first arg since the
2nd.arg might be evaluated first - on failure it would then overwrite the
first arg)

May 8 '07 #2
Thanks for the feedback:
The only way that GetLastWin32Err or is going to return a different value
is if you use another call to unmanaged code. You should store the error
if you are going to perform an operation which could possibly change it,
and you need it for later.
I won't be calling unmanaged code directly. My concern are calls that .NET
itself makes. Those calls will invoke "SetLastError() " in the WinAPI but
does this affect "Marshal.GetLas tWin32Error()" for clients (i.e., me). Note
that I can always save the result before throwing the exception (passing
this value to the constructor) but I'd like to know what the rules are.
I am curious, why are you passing an error string or the last error to the
Win32Exception class? If you use the default constructor, it should get
the value of the last win 32 error and also create the appropriate
exception message.
I'm still experimenting but I want to capture context info at the time of
call (the parameters that caused the failure for instance). Take this as a
possible solution for example (which I'm still considering):

class Win32LastError : Win32Exception
{
public Win32LastError( string messageEx)
{
m_MessageEx = messageEx;
}

public string MessageEx
{
get
{
return m_MessageEx;
}
}

private string m_MessageEx;
}

When the base class' default constructor is called, could the last error
have already been overwritten during construction of the "messageEx"
parameter itself (in the above constructor). It relies on the WinAPI behind
the scenes so it could potentially change the last error before the base
class constructor even starts (or so I'm speculating). This would be
particularly true if a non-trivial expression is used to create the string
in the first place (at the point of call). Note that this won't involve
unmanaged code however.
May 8 '07 #3
Larry,

The GetLastWin32Err or method will only return the value of GetLastError
for P/Invoke calls, not for CLR internal calls (as the documentation
states). Because of this, you only have to worry about the code being
changed if another call on the same thread makes another call through the
P/Invoke layer.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Larry Smith" <no_spam@_nospa m.comwrote in message
news:eR******** ********@TK2MSF TNGP03.phx.gbl. ..
Thanks for the feedback:
>The only way that GetLastWin32Err or is going to return a different value
is if you use another call to unmanaged code. You should store the error
if you are going to perform an operation which could possibly change it,
and you need it for later.

I won't be calling unmanaged code directly. My concern are calls that .NET
itself makes. Those calls will invoke "SetLastError() " in the WinAPI but
does this affect "Marshal.GetLas tWin32Error()" for clients (i.e., me).
Note that I can always save the result before throwing the exception
(passing this value to the constructor) but I'd like to know what the
rules are.
>I am curious, why are you passing an error string or the last error to
the Win32Exception class? If you use the default constructor, it should
get the value of the last win 32 error and also create the appropriate
exception message.

I'm still experimenting but I want to capture context info at the time of
call (the parameters that caused the failure for instance). Take this as a
possible solution for example (which I'm still considering):

class Win32LastError : Win32Exception
{
public Win32LastError( string messageEx)
{
m_MessageEx = messageEx;
}

public string MessageEx
{
get
{
return m_MessageEx;
}
}

private string m_MessageEx;
}

When the base class' default constructor is called, could the last error
have already been overwritten during construction of the "messageEx"
parameter itself (in the above constructor). It relies on the WinAPI
behind the scenes so it could potentially change the last error before the
base class constructor even starts (or so I'm speculating). This would be
particularly true if a non-trivial expression is used to create the string
in the first place (at the point of call). Note that this won't involve
unmanaged code however.

May 8 '07 #4
The GetLastWin32Err or method will only return the value of GetLastError
for P/Invoke calls, not for CLR internal calls (as the documentation
states). Because of this, you only have to worry about the code being
changed if another call on the same thread makes another call through the
P/Invoke layer.
I just assumed as much and the docs basically say so but I didn't want to
get tripped up with subtle problems later (since I'm relatively new to
..NET). Thanks very much for your help.
May 8 '07 #5

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

Similar topics

13
2171
by: Just Me | last post by:
The following almost works. The problem is Marshal.PtrToStringAuto seems to terminate at the first null so I don't get the full string. Any suggestions on how to fix this? Or how to improve the code? Thanks PS I added the +1 because as I understand the GetLogicalDriveStrings doc
6
2722
by: william.thorpe.b | last post by:
I have recently switched from VS2003 to VS2005 and at the same time from V1 to V2 of the .NET Compact Framework. The target is a Windows CE 5.0 device and an ARMV4I processor. System.Runtime.InteropServices.Marshal.WriteInt32 used to work fine but now is misbehaving. I wrote some native-code (C++) alternates to some Marshal methods and when I P/Invoke them they work fine; I can write to an address and I read back the same value that...
2
1924
by: Pierre Rouleau | last post by:
Hi all, When using Python 2.4.x on a Win32 box, marshal.loads(marshal.dumps(1e66666)) returns 1.0 instead of infinity as it should and does under Python 2.5 (also running on Win32 ). This problem was reported in another thread here by Peter Hansen http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/5c2b4b2a88c8df4/f216739705c9304f?lnk=gst&q=simplejson&rnum=5#f216739705c9304f Is this considered an important enough...
10
2166
by: active | last post by:
GetLastWin32Error exposes the Win32 GetLastError API method from Kernel32.DLL. This method exists because it is not safe to make a direct platform invoke call to GetLastError to obtain this information. If you want to access this error code, you must call GetLastWin32Error rather than writing your own platform invoke definition for GetLastError and calling it. The common language runtime can make internal calls to APIs that overwrite the...
5
1995
by: Anurag | last post by:
I have been chasing a problem in my code since hours and it bolis down to this import marshal marshal.dumps(str(123)) != marshal.dumps(str("123")) Can someone please tell me why? when str(123) == str("123") or are they different?
2
7209
by: O.B. | last post by:
When using Marshal to copy data from a byte array to the structure below, only the first byte of the "other" array is getting copied from the original byte array. What do I need to specify to get Marshal.PtrToStructure to copy the all the data into the "other" array? unsafe public struct DeadReckoning {
0
2138
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)
0
2741
by: xrxst32 | last post by:
Hello there, I have some doubts about the best practice for using COM automation, the Runtime Callable Wrapper (RCW) and Marshal.ReleaseComObject. So the question is/are: Do I need to release each COM object explicit by a call to Marshal.ReleaseComObject, does the RCW take care of that or does it leaks unmanaged resources?
2
15950
by: O.B. | last post by:
I have operation within a class that marshals the data into a byte array. Below are three different ways that work. Are there any downsides to using one over the the other? public virtual byte ToRaw1() { byte byteArray = new byte; IntPtr pointer = Marshal.AllocHGlobal(Size); Marshal.StructureToPtr(this, pointer, false); Marshal.Copy(pointer, byteArray, 0, Size);
0
9699
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
9562
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
10304
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
10285
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
10063
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9114
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
7598
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
5494
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...
1
4270
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.