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: - [DllImport("MyDll.dll", EntryPoint = "MyFunction", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
-
private unsafe static extern int MyFunction(void* results, void* values);
-
-
private void CallFunction()
-
{
-
int returnStatus = 0;
-
IntPtr resultPtr = IntPtr.Zero;
-
IntPtr valPtr = IntPtr.Zero;
-
int[] rawResults = new int[RESULT_SIZE];
-
double[] rawValues = new double[RESULT_SIZE];
-
-
try
-
{
-
// Allocate memory
-
resultPtr = Marshal.AllocHGlobal(RESULT_SIZE * sizeof(int));
-
valPtr = Marshal.AllocHGlobal(RESULT_SIZE * sizeof(double));
-
-
// Call external function
-
unsafe
-
{
-
returnStatus = MyFunction(resultPtr.ToPointer(), valPtr.ToPointer());
-
}
-
-
Marshal.Copy((IntPtr)resultPtr, rawResults, 0, RESULT_SIZE);
-
Marshal.Copy((IntPtr)valPtr, rawValues, 0, RESULT_SIZE);
-
}
-
catch (Exception e)
-
{
-
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);
-
MessageBox.Show(errMsg, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
-
}
-
finally
-
{
-
if (resultPtr != IntPtr.Zero)
-
Marshal.FreeHGlobal(resultPtr);
-
if (valPtr != IntPtr.Zero)
-
Marshal.FreeHGlobal(valPtr);
-
}
-
}
-
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
1 8104
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: -
{
-
public const int RESULT_SIZE = 10;
-
-
[DllImport("MyDll.dll", EntryPoint = "MyFunction", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
-
private static extern int MyFunction(int[] results, double[] values);
-
-
public int MyFunctionWrapper
-
{
-
int returnStatus = 0;
-
int[] rawResults = new int[RESULT_SIZE];
-
double[] rawValues = new double[RESULT_SIZE];
-
-
returnStatus = MyFunction(rawResults, rawValues);
-
-
if (returnStatus == 0)
-
{
-
// Do something with data
-
return returnStatus;
-
}
-
else
-
{
-
// Throw new exception
-
return returnStatus;
-
}
-
}
-
}
-
-
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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. ...
|
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...
|
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
|
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!
| |
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...
|
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
|
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...
|
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...
|
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...
|
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,...
| |
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |