473,769 Members | 3,305 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Unamanged Code Causing Access Violations

6 New Member
Hey all -

I have some unmanaged code that I'm calling into with C# .NET 2.0, and everything works flawlessly in the debugger, but as soon as I run the application as a standalone executable it unexpectedly quits without throwing any exceptions. Even if I start the executable in the debugger it works okay. To see the failure, I need to start the application and then attach the debugger to the process. The function call will work okay twice and the data comes out okay, but on the third call it shuts down without any notice.

When running with Windows Debugging Tools I can see the access violation ("Access violation - code c0000005") and I'm pretty sure it's a NULL pointer exception, but can't figure out why or what to do about it.

I suspect it's because of the garbage collector moving data around, but I thought that the way I had created and passed the pointers in that they would be pinned.

The unmanaged function takes an input of int*, and double*, which it modifies during it's execution.

Here's a short code sample of the calling convention:

Expand|Select|Wrap|Line Numbers
  1. [DllImport("MyDll.dll", EntryPoint = "MyFunction", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
  2. private unsafe static extern int MyFunction(void* results, void* values);
  3.  
  4. private void CallFunction()
  5. {
  6.     int returnStatus = 0;
  7.     IntPtr resultPtr = IntPtr.Zero;
  8.     IntPtr valPtr = IntPtr.Zero;
  9.     int[] rawResults = new int[RESULT_SIZE];
  10.     double[] rawValues = new double[RESULT_SIZE];
  11.  
  12.     try
  13.     {
  14.         // Allocate memory
  15.         resultPtr = Marshal.AllocHGlobal(RESULT_SIZE * sizeof(int));
  16.         valPtr = Marshal.AllocHGlobal(RESULT_SIZE * sizeof(double));
  17.  
  18.         // Call external function
  19.         unsafe
  20.         {
  21.             returnStatus = MyFunction(resultPtr.ToPointer(), valPtr.ToPointer());
  22.         }
  23.  
  24.         Marshal.Copy((IntPtr)resultPtr, rawResults, 0, RESULT_SIZE);
  25.         Marshal.Copy((IntPtr)valPtr, rawValues, 0, RESULT_SIZE);
  26.     }
  27.     catch (Exception e)
  28.     {
  29.         string errMsg = String.Format("An exception has been caught attempting to call the external function. The following exception was trapped:\n\n{0}", e.Message);
  30.         MessageBox.Show(errMsg, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
  31.     }
  32.     finally
  33.     {
  34.         if (resultPtr != IntPtr.Zero)
  35.             Marshal.FreeHGlobal(resultPtr);
  36.         if (valPtr != IntPtr.Zero)
  37.             Marshal.FreeHGlobal(valPtr);
  38.     }
  39. }
  40.  
I've been trying to figure out the best way to go about doing this, and at one time had tried using a structure with fixed variables, but that was also victim to the same problems. I like this approach better and seems more reliable but it's still crashing.

Any help is much appreciated!

Thanks
Sep 19 '08 #1
1 8104
tk121
6 New Member
Well, in case someone stumbles upon something similar in the future, I thought I would post that I found the solution to this problem.

I did some more digging and realized that with data types int, and double supported natively by .NET, there is no need to manually create memory space and marshal the datatypes. Managed arrays passed into the function work just as well. The memory allocation was way overkill.

It doesn't seem as though this is affected by the garbage collector either.

Once I realized that the issue was not related to the .NET code, I began digging for issues with the DLL and the unmanaged code.

Apparently the function in the unmanaged code had too many static initializers that were eating up all the stack space. It would run fine once until the stack space was depleted and after that would throw null pointer references.

So I'm guessing the reason the code worked in the .NET debugger all the time was that the stack space for the DLL was pulled from the heap as opposed to the default for the compiled DLL. As soon as the executable ran on it's own it used the default stack space which was much lower causing the application to crash after a couple runs without throwing an exception. Just a guess, but I'm glad I finally found a solution to this.

If anyone can confirm or deny my suspicions (or provide an explanation), I would like to hear to any other ideas.

Here's a sample of what the new C# source looks like after cleaning it up:

Expand|Select|Wrap|Line Numbers
  1. {
  2.     public const int RESULT_SIZE = 10;
  3.  
  4.     [DllImport("MyDll.dll", EntryPoint = "MyFunction", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
  5.     private static extern int MyFunction(int[] results, double[] values);
  6.  
  7.     public int MyFunctionWrapper
  8.     {
  9.         int returnStatus = 0;
  10.         int[] rawResults = new int[RESULT_SIZE];
  11.         double[] rawValues = new double[RESULT_SIZE];
  12.  
  13.         returnStatus = MyFunction(rawResults, rawValues);
  14.  
  15.         if (returnStatus == 0)
  16.         {
  17.             // Do something with data
  18.             return returnStatus;
  19.         }
  20.         else
  21.         {
  22.             // Throw new exception
  23.             return returnStatus;
  24.         }
  25.     }
  26. }
  27.  
  28.  
Sep 20 '08 #2

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

Similar topics

15
18031
by: Steven Reddie | last post by:
I understand that access violations aren't part of the standard C++ exception handling support. On Windows, a particular MSVC compiler option enables Microsoft's Structured Exception Handling (SEH) in C++ EH so that a catch (...) will catch an access violation. I don't know if other platforms support something similar. I'm wondering about how to best protect an application or library from poorly written user-defined callbacks. It...
0
2724
by: Steven Reddie | last post by:
In article <slrnbnj19j.av.juergen@monocerus.manannan.org>, Juergen Heinzl wrote: >In article <f93791bd.0309282133.650da850@posting.google.com>, Steven Reddie wrote: >> I understand that access violations aren't part of the standard C++ >> exception handling support. On Windows, a particular MSVC compiler >> option enables Microsoft's Structured Exception Handling (SEH) in C++ >> EH so that a catch (...) will catch an access violation. ...
3
2674
by: Yossi Kreinin | last post by:
Hi! Is there a summary of the rules C++ code should obey, but an implementation doesn't have to verify it does? For example, the one definition rule or the prohibition to dereference a null pointer. Such a summary could be extracted from the standard, perhaps it already was? There are also a lot of tools looking for SOME of such violations. Is there a tool that could guarantee something like: "ALL compile-time violations will be...
14
10144
by: Abhi | last post by:
FYI: This message is for the benefit of MS Access Community. I found that this prblem has been encounterd by many but there is hardly any place where a complete solution is posted. So I thought I should give back to the community by posting our findings. Thanks you all for all your help till now by posting problems and their solutions. ~Abhijit
12
2395
by: technocrat | last post by:
I am trying to laod 2 tables and set integrtiy on them, but the second tables fails ( both are related and SET INTEGRITY ion first table succeeds) saying constraint violation....is there a way to find out which records are violating....?? may be through try catch a SQLException...??? but how?? any suggestions are welcome!
13
5327
by: mfreeman | last post by:
The minimal code (VB.NET 2003) needed to show this problem is shown below. All I do is loop through the records in the table and update them without making any changes. Out of 600 records, about 40 of them throw Concurrency violation errors in the update, and my GetAllColErrs function provides no output. In comparing the rows that throw errors with those that do not, I could find no pattern. It is obviously a bogus error, as the...
2
1570
by: Willem Voncken | last post by:
Hi guys, might be a silly question, but i'm wondering whether it is even possible to generate access violations when using C#? I'm new at c# programming, but i have some experience with c++. Now that i'm using c# i can't see how i should mess up memory like that without the use of pointers or adresses. Regards, Willem
0
1367
by: krishnasamy | last post by:
Hello, I am writing a DLL for Capturing the Image from Camera Device using Camera SDK DLL. All the calls made to functions in Camera SDK DLL are working properly as I am able to get a return value of zero. I am able to get the image data as unmanaged memory address(pointer) as a result of a functions call to the camera SDK. I do not know how to display this data directly in the interface using the bitmap class without copying the same to...
1
1791
by: Viperoptic | last post by:
Hi All I am doing an update query from MS Access on a few records. The update work once perfectly but a soon as I run it again it returns the error below... "I have 5 records that won't do what its told due to key violations Database didn't update 0 field(s) die to a type conversion failure, 5 record(s) due to key violations, 0 record(s) due to lock violations and 0 record(s) die to validation rule violations. " Is there anyway...
0
9589
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
9423
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
10216
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...
0
8873
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...
0
6675
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
5310
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
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
2
3565
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.