473,324 Members | 2,124 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,324 software developers and data experts.

Why does Marshal.FreeHGlobal Fail?

Hello,

I am fairly new to all this and I am hoping somone can help. I am writing a C# application that requires use of the Clipborad for inter-process communication. C# has methods I can leverage in order to accomplish this:

Expand|Select|Wrap|Line Numbers
  1. Clipboard.SetText(string);
  2.  
Unfortunately, there is an unacceptable delay when using this call. The receiving process does not recognize its presence for over 5 seconds. As such, I moved onto native Win32 SDK calls. Namely: SetClipboardData() and its required support functions. This call gives me the speed I require as the contents are transferred near immediately to the clipboard when I use the native methods. Unfortunately, the call to free allocalted heap memory fails like clockwork on the fourth iteration.
When I comment out the FreeHGlobal function (bad juju...), everything operates as expected. Here is the class I use to use call the native methods:

Expand|Select|Wrap|Line Numbers
  1. class ClipboardHelper
  2. {
  3.     [DllImport("user32.dll")]
  4.     static extern bool OpenClipboard(IntPtr hWndNewOwner);
  5.     [DllImport("user32.dll")]
  6.     static extern bool EmptyClipboard();
  7.     [DllImport("user32.dll")]
  8.     static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem);
  9.     [DllImport("user32.dll")]
  10.     static extern bool CloseClipboard();
  11.     [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)
  12.     public static extern IntPtr GlobalFree(IntPtr handle);
  13.  
  14.     static public bool PutTextOnClipboard(IntPtr hWnd, StringBuilder s)
  15.     {   
  16.         bool bResult = false;   
  17.  
  18.         if (OpenClipboard(hWnd))   
  19.         {      
  20.             IntPtr ptr = Marshal.StringToHGlobalAnsi(s.ToString());      
  21.  
  22.             if (EmptyClipboard())      
  23.             {         
  24.                 IntPtr hRes = SetClipboardData(1 /*CF_TEXT*/, ptr);
  25.                 CloseClipboard();
  26.             }      
  27.  
  28.             Marshal.FreeHGlobal(ptr);
  29.            //GlobalFree(ptr);
  30.         }   
  31.  
  32.         return true;
  33. }
  34.  
The top level exception is:
Expand|Select|Wrap|Line Numbers
  1. An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
  2.  

Does anyone have any idea what I am doing wrong here?

Partial stack trace:
Expand|Select|Wrap|Line Numbers
  1. mscorlib.dll!System.AccessViolationException.AccessViolationException() + 0x14 bytes 
  2.  
  3. [Native to Managed Transition] 
  4.  
  5. [Managed to Native Transition] 
  6.  
  7. mscorlib.dll!System.Reflection.CustomAttributeEncodedArgument.ParseAttributeArguments(System.Reflection.ConstArray attributeBlob, ref System.Reflection.CustomAttributeCtorParameter[] customAttributeCtorParameters, ref System.Reflection.CustomAttributeNamedParameter[] customAttributeNamedParameters, System.Reflection.RuntimeModule customAttributeModule) + 0x5b bytes 
  8.  
  9. mscorlib.dll!System.Reflection.CustomAttributeData.CustomAttributeData(System.Reflection.RuntimeModule scope, System.Reflection.CustomAttributeRecord caRecord) + 0x4c4 bytes 
  10.  
  11. mscorlib.dll!System.Reflection.CustomAttributeData.GetCustomAttributes(System.Reflection.RuntimeModule module = {System.Reflection.RuntimeModule}, int tkTarget) + 0x53 bytes 
  12.  
  13. mscorlib.dll!System.Reflection.CustomAttributeData.GetCustomAttributesInternal(System.Reflection.RuntimeAssembly target = {System.Reflection.RuntimeAssembly}) + 0x47 bytes 
  14.  
  15. mscorlib.dll!System.Reflection.RuntimeAssembly.GetCustomAttributesData() + 0x5 bytes 
  16.  
  17. mscorlib.dll!System.Reflection.CustomAttributeData.GetCustomAttributes(System.Reflection.Assembly target) + 0x21 bytes 
  18.  
  19. mscorlib.dll!System.Resources.ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(System.Reflection.Assembly a = {System.Reflection.RuntimeAssembly}, ref System.Resources.UltimateResourceFallbackLocation fallbackLocation = MainAssembly) + 0x31 bytes 
  20.  
  21. mscorlib.dll!System.Resources.ResourceManager.CommonSatelliteAssemblyInit() + 0x6d bytes 
  22.  
  23. mscorlib.dll!System.Resources.ResourceManager.ResourceManager(string baseName, System.Reflection.Assembly assembly = {System.Reflection.RuntimeAssembly}) + 0x51 bytes 
  24.  
  25. mscorlib.dll!System.Environment.ResourceHelper.GetResourceStringCode(object userDataIn) + 0x111 bytes 
  26.  
  27. [Native to Managed Transition] 
  28.  
  29. [Managed to Native Transition] 
  30.  
  31. mscorlib.dll!System.Environment.ResourceHelper.GetResourceString(string key, System.Globalization.CultureInfo culture) + 0xd1 bytes 
  32.  
  33. mscorlib.dll!System.Environment.GetResourceStringLocal(string key) + 0x48 bytes 
  34.  
  35. [Native to Managed Transition] 
  36.  
  37. [Managed to Native Transition] 
  38.  
  39. mscorlib.dll!System.Runtime.InteropServices.COMException.COMException() + 0x14 bytes [Native to Managed Transition] [Managed to Native Transition] 
  40.  
  41. mscorlib.dll!System.Runtime.InteropServices.Marshal.FreeHGlobal(System.IntPtr hglobal) + 0x74 bytes
  42.  
Aug 16 '10 #1
2 5030
Please note that Clipboard-based inter-process communication is not a choice I have made because I thought it was a great idea. I am using this methodology because the receiving process API is already defined and I have no control over it.
Aug 16 '10 #2
Plater
7,872 Expert 4TB
Hmmm have you verified that the pointer returned from StringToHGlobalAnsi() is valid and not a null pointer?

I just ran a loop through your code 10 times and it worked everytime without fail.
Are you trying to do something else with pointers?


EDIT: Also, do you need to be doing anything with IntPtr hRes? Should that also get free'd?
Aug 19 '10 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

12
by: | last post by:
I issued the mysql command Grant all on *.* to myid@localhost identified as "mypw"; and recieved the error message ERROR 1045: Access denied for user" '@localhost' (Using password: NO) I...
2
by: Fei Li | last post by:
Hi, After converting String* to Char*, I need to call Marshal::FreeHGlobal(). Fine. But I need pass this Char* to an unmagaed C++ class and the managed C++ class is not possible to do...
2
by: deko | last post by:
Why am I getting: "Error Number 70: Permission denied" when trying to move a folder with the Microsoft Scripting Runtime? Is there some security setting I don't know about? Platform: Windows...
3
by: 4partee | last post by:
I'm trying to import a csv file with a PHP procedure. However, some of the lines in the csv file have missing values. When this command is given to mysql: insert tablex values...
13
by: David Thielen | last post by:
XPathNavigator nav = MyCreateNav(); // InnerXml == "software" nav.SelectSingleNode"."); The select returns an exception: + $exception {"'.' has an invalid token."} System.Exception...
9
by: David Thielen | last post by:
Hi; I am sure I am missing something here but I cannot figure it out. Below I have a program and I cannot figure out why the xpath selects that throw an exception fail. From what I know they...
12
by: deko | last post by:
I have a long page with several sections and want to link to these sections from another page like this: <a href='http://www.mysite.com/content.html#section12'>Section 12</a> Here's what the...
11
by: sgadag | last post by:
Even if "a" is NULL in the assignment below, this assignment does not cause any AV: SOME_PTR * someVar = (SOME_PTR *) a->b; But something like this will cause an AV because "someVar" is...
6
by: lawrence k | last post by:
Wierd. Go to this page: http://www.ihanuman.com/search.php and search for "yoga" This query gets run: SELECT * FROM albums WHERE MATCH(name,description) AGAINST ('yoga') ORDER BY id DESC
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.