this message is appearing in C# code after calling a function from dll
code is like this
function();
int i = 0;
on second line it says that there is an unhandled exception of type "System.AccessViolationException"... Attempted to read or write protected memory
If function is external there's something wrong with the declaration.
This happens because your return value or your parameters types aren't of the wrong size, and an error occurs with data "popped" from stack
Related
I’ve compiled libsass 3.3.6 into a DLL with VS 2015 using the included solution files. Running the code below causes the program to crash immediately with no output.
using System;
using System.Runtime.InteropServices;
namespace Sass.Cli {
static class Sass {
[DllImport(#"C:\...\libsass\win\bin\libsass.dll")]
public static extern String libsass_version();
}
class Program {
static void Main(string[] args) {
Console.WriteLine(Sass.libsass_version());
}
}
}
The source for the invoked function is at sass.cpp:61.
const char* ADDCALL libsass_version(void)
Both the DLL and the above code were compiled for x86. Running the VS debugger on crash gives me the following exception: Unhandled exception at 0x771A9841 (ntdll.dll) in Sass.Cli.exe: 0xC0000374: A heap has been corrupted (parameters: 0x771DC8D0).
Is this something that can be fixed or that I’ve overlooked? Or is it just the case that libsass DLLs aren’t currently working?
When a string is used as a return type then the framework assumes it was allocated by calling CoTaskMemAlloc. It then copies the content of the string and deallocation by calling CoTaskMemFree. That is the explanation for your error.
Solve it by changing the return value to IntPtr and getting the string content with Marshal.PtrToStringAnsi. You won't need to deal located anything since this version string will be static.
I can't tell what the calling convention is. You should check the code and docs to find out. Still, this function is so simple that it behaves the same way for both cdecl and stdcall so that can't explain the error. Still, you will need to get it right for the rest of the library.
Note that I am guessing a little here. You've not provided full details. You should consult the code and docs to double check my guesswork.
I have an Excel function that I'm calling from C# as follows:
string result = xlApp.Run("'ExcelBook.xlsm'!mainFromBatch",
"http://someSite/TestFile.xlsm",
false,
"T:\\somePath");
When run, this raises an error:
An exception of type 'System.Runtime.InteropServices.COMException' occurred
in BatchConverter.exe but was not handled in user code
Additional information: Exception from HRESULT: 0x800ADF09
If there is a handler for this exception, the program may be safely continued.
The function header for mainFromBatch is:
Function mainFromBatch(sourceBkPath As String, Flag As Boolean, _
Optional outputPathFromConfig As String) As String
When I put a breakpoint at this function header in the VBA code of ExcelBook.xlsm, the C# code raises the error, but the Excel breakpoint is reached and Excel pauses there, as though no error had occurred and it's ready to execute the rest of the code.
I'm able to use C# to call other functions from this workbook without a problem.
I tried Googling the HRESULT code but didn't find anything.
Any idea what's going on here?
I am working on a project that requires implementing am unmanaged windows DLL. The DLL is used to communicate with a USB device. My code is in C# and WPF.
To initialize the DLL I call a function called:
InitTimerDll(Int32 wHandle, ref dllInitParams initParams);
When calling this function I have to pass a struct called dllInitParams and the Handle that the control is bound to.
I am using DllImport for function pointer as such:
[DllImport("myDll.dll")]
public static extern void InitTimerDll(Int32 wHandle, ref dllInitParams initParams);
Here is my struct:
public struct dllInitParams
{
public UInt16 simp;
public UInt16 simt;
}
All of the above are in a separate class called myDllInterface.cs. Here is how I call the InitTimerDll function from my WPF form:
public IntPtr Handle
{
get { return (new System.Windows.Interop.WindowInteropHelper(this)).Handle; }
}
private void initTime_Click(object sender, RoutedEventArgs e)
{
myDllInterface.dllInitParams initParams = new myDllInterface.dllInitParams();
initParams.simp = 0;
myDllInterface.InitTimerDll(this.Handle.ToInt32(), ref initParams);
}
The first part of the above code explains how I get the handle and the initTime_Click shows how I initialize the struct, call the initTimeDll function by passing the handle and the struct to it. I have copied the dll file in the directory that the code runs in. My code compiles just fine but it creates an error when I click on the initTime button.
Error:
An unhandled exception of type 'System.AccessViolationException' occurred in ProbeCTRL.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Why is this happening?
Without knowing exactly what the InitTimerDll() function does with the 'this' pointer, I would focus on the params structure. Try adding a structure layout markup like the following:
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct dllInitParams
{
public UInt16 simp;
public UInt16 simt;
}
Also, double check that your structure is complete and accurate.
I found the problem. The code is fine the problem was the dll file, which was corrupted. A proper copy of the dll file took care of the problem. When using dll in your codes it is quite important to make sure you have accurate information, function calls, data types to passed and so on.
Thanks everyone for your help.
Have a look at the PInvoke tutorial: http://msdn.microsoft.com/en-us/library/aa288468%28v=vs.71%29.aspx
as Jim Gomes points out:
[StructLayout(LayoutKind.Sequential)]
or something similar is definitely important.
Also, you're only initializing one of the variables in your struct.
I've a delegate to an unmanaged function on a DLL (which I loaded using GetProcAddress). I can call this delegate with no trouble. When I call the delegates with BeginInvoke, however, I get the following exception:
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in '...'.
Additional Information: The runtime has encountered a fatal error. The address of the
error was at 0x63fd8687, on thread 0xb4c. The error code is 0xc0000005. This error may
be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common
sources of this bug include user marshaling errors for COM-interop or PInvoke, which
may corrupt the stack.
This is the code:
private void OnConnectFinished(IAsyncResult a_oResult)
{
ConnectDelegate l_oDelegate = (ConnectDelegate)a_oResult.AsyncState;
if (ConnectFinished != null)
{
ConnectFinished(l_oDelegate.EndInvoke(a_oResult));
}
}
public bool Connect()
{
AsyncCallback l_oCallback = new AsyncCallback(OnConnectFinished);
IAsyncResult l_oResult = DLLConnect.BeginInvoke(l_oCallback, DLLConnect);
//This Works!:
//bool l_bResult = DLLConnect(m_oConnectFinishedDelegate);
//return l_bResult;
return true;
}
Any ideas on why is this happening?
Passing the delegate as userState (the second argument in BeginInvoke) seems suspicious. Will it work if you pass null there? (Yes, I know that your callback won't work, but this issue can be handled another way. Let's check if the reported error disappears.)
I am getting exception when i am trying to pass unmanaged object, to COM method in method written in managed C++/CLI class. Following is the code sample
//C++/CLI class
public ref class PSIAAdaptorManagedWrapper
{
CConfiguration *Configuration;
void InitializeConfig();
}
//C++/CLI Method implementation
void PSIAAdaptorManagedWrapper::InitializeConfig() {
Configuration = new CConfiguration();
Configuration->IPAddress = "127.0.0.1";
Configuration->UserName = "User";
Configuration->password = "password";
SomeComObject->GetInitiConfig((void *) Configuration); // Exception line
}
//signature of COM object from IDL file (observer paramer it takes is in)
[helpstring("method InitializeCameraConfig")]
HRESULT GetInitiConfig([in] void *configparam);
Above code compiles fine. But when execute I get "System.AccessViolation" runt time error on line. I think it is because, I am trying to allocate unmanaged memory in managed function. But I am not sure how to get around this.
It could be possible that a user name or password are incorrect. AccessViolation is best noted for those issues.
Also, I dont see why anything should go wrong the way you are handling things in your code above.