Home » VB.Net

AccessViolationException - Calling Unmanaged Code - Byref...

Hi there

I was calling this C++ function from vb and i got the error "Attempted to read or write protected memory..."

Here's the code:
The prototype of the API is:

voidWINAPIAvzGetImage(unsigned short DeviceID, unsigned char *Image,unsigned short FingerOn)

DeviceID = Device ID
Image = Data Of The Image
FingerOn = Is always 1

So, in vb, i tried calling it using:

Declare Auto Sub AvzGetImage Lib "AvzScanner.dll" (ByVal DID As UShort, ByRef img() As Byte, ByVal finger As UShort)
Dim img(280 * 280 - 1) as Byte
AvzGetImage(0, img, 1)



However, it would return me the stated error. Anyone any idea? =D



1 Answer Found


Answer 1

Based upon the C++ signature I end up with the following (using P/Invoke Interop Assistant ):

Partial Public Class NativeMethods
 '''Return Type: void
 '''DeviceID: unsigned short
 '''Image: unsigned char*
 '''FingerOn: unsigned short
 <System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint:="AvzGetImage")> _
 Public Shared Sub AvzGetImage(ByVal DeviceID As UShort, ByVal Image As System.IntPtr, ByVal FingerOn As UShort)
 End Sub
End Class


If the signature is correct (I don't know what Image is returning) I'm assuming that Marshal.PtrToStringAuto will get you the data:


Dim StringBuffer As String = Marshal.PtrToStringAuto(Image)

Paul ~~~~ Microsoft MVP (Visual Basic)

The situation isn't as clear cut as the previous posts (by other people) make it to be. My case differs because of the following:

I have a C# application calling a Native C++ DLL via PInvoke.
The symptoms of the problem are as follows:
If I run the code, nothing breaks (Press F5).
If I run the code and hitting a breakpoint in the code, subsequently running the code again (Press F5), nothing breaks.

Basically I can always run the code and traverse via F5.

If I run the code and hit a breakpoint in the unmanaged area, when I subseqently step through (press F10, or F11) I get:
First-chance exception at 0x0926f77b in <Program Name>: 0xC0000005: Access violation.
First-chance exception at 0x739a5015 (mscorwks.dll) in <Program Name>: 0xC0000005: Access violation reading location 0x0926f77b.
First-chance exception at 0x739a5015 (mscorwks.dll) in <Program Name>: 0xC0000005: Access violation reading location 0x0926f77b.
The thread 'Win32 Thread' (0x1604) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0xf00) has exited with code 0 (0x0).
The thread 'Win32 Thread' (0x12b4) has exited with code 0 (0x0).
A first chance exception of type 'System.AccessViolationException' occurred in <Program Name>

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Misc Junk Follows.

Finally, lets use this example to explain the next bit of information

1: void ManagedFunction()
2: {
3:        UnManagedFunction(bC.Handle, address, ref ytArray[0], bytArray.Length, ref EC);
4: }

10: void UnManagedFunction(UInt32 Handle, Int32 address, ref Byte bytArray, Int Length, ref Int EC)
11: {
12:       //blah.....
13: }

Note: Syntactically the entire line is correct and compiles regardless of whether I have made a mistake above.

I (can) hit F11 on line 3 and step to line 11.
I (Can NOT) hit F10 or F11 on line 11 as it will throw the exception.
I (can) place a break point on line 13 and hit F5 and get to the breakpoint without error.

The access error only appears when stepping through code. Though, stepping through the code is a necessary part of debugging I would like to fix this error if possible.


I have created an API in C# that I wish to call from unmanaged C++ code.  I have found a few articles which detail how to disassemble, alter, and reassemble the MSIL once it is compiled.  The problem is that my assemblies will all be generated by Platform Builder as part of a complete OS image, so I do not have the luxury of editing the MSIL by hand, after the fact.

I have also found articles that talk about passing a delegate to the unmanaged code via:

delegate int MyUnmanagedCdeclDelegate(int param);
But the only way that I have seen this used is for the C# program to first call the unmanaged code so that it can pass the function pointer, and then the unmanaged code can use it (so long as the delegate does not get garbage collected.)

Is there any way that the unmanaged code can initiate this whole process?  Like I said, I am trying to create an API, so I need any arbitrary unmanaged code to be able to call into my managed dll.  Is this at all possible?  I wouldn't even mind having some sort of intermediate dll that is called from the unmanaged code, which in turn calls into the managed dll.

I could really use a push in the right direction here, if this is even possible.  I have read through heaps of articles, but they all seem to point me in the same direction: The C# program passes a function pointer to the native method, and then calls other native methods which use the callback delegate that was passed.  Maybe I am missing something, but I don't understand the utility of that setup.

Thanks in advance for any tips or articles that can help.



I have a unmanaged C++ DLL. I want to use it without DllImport but using LoadLibrary, FreeLibrary and GetProcAddress to get the function pointer of each function exported. My problem is the following : how can I call a function pointer in .Net Compact Framework 2.0 ? The .Net Framework has Marshal.GetDelegateFromFunctionPointer, but this function doesn't exist in CF 2.0.

Any idea,



Couple of months ago I had to use some dll written in C in my C# project. I somehow managed to write a wrapper class (never done this before) and it worked on Windows XP. Now I have Windows 7 installed and the code won't work. Application is quite simple, I have to read some data from a smart card using USB reader and dll provides methods to do so. First I call dll function to initialize device, then initialize reading, read data, end reading, release device.
My wrapper class looks something like this
[SuppressUnmanagedCodeSecurity()] //newly added, not helping
    public class myIDUnsafeNativeMethods
        [DllImport(GlobalConstants.myIDApi, CharSet = CharSet.Unicode)]
        static internal extern int EidStartup(
            int nApiVersion

        [DllImport(GlobalConstants.myIDApi, EntryPoint = "EidCleanup", CharSet = CharSet.Unicode)]
        static internal extern int EidCleanup(

        [DllImport(GlobalConstants.myIDApi, CharSet = CharSet.Unicode)]
        static internal extern int EidReadFixedPersonalData(
            ref tagEID_FIXED_PERSONAL_DATA pData

        [DllImport(GlobalConstants.myIDApi, CharSet = CharSet.Unicode)]
        static internal extern int EidReadDocumentData(
            ref tagEID_DOCUMENT_DATA pData

[DllImport(GlobalConstants.myIDApi, CharSet = CharSet.Unicode)]
static internal extern int EidBeginRead(
[MarshalAs(UnmanagedType.LPStr)] String szReader

And the part where I use the code
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] //newly added, not helping
        public myResult ReadData()
            myResult tmpResult = new myResult();
            int ret;
            ret = myIDUnsafeNativeMethods.EidBeginRead(_deviceName);
            if (ret < 0)
                tmpResult.errorCode = ret;
                tmpResult.errorMessage = GetErrorMessage(ret) + " _EidBeginRead";
                return tmpResult;
            ret = myIDUnsafeNativeMethods.EidReadDocumentData(ref tmpResult.eIdDocumentData);
            if (ret < 0)
                tmpResult.errorCode = ret;
                tmpResult.errorMessage = GetErrorMessage(ret) + " _EidReadDocumentData";
                return tmpResult;
The code fails in a call to ReadDocumentData and that is what confuses me the most. It initializes without an error, but when I try to read data it returns reader error (error code from the dll specification). I noticed that USB device name is different in Windows 7 (same card reader), I tried updating card reader drivers, it doesn't help. That is why I think it has to do something with security and permissions for calling unmanaged code, and I tried setting
but it didn't help.

Any fresh ideas?

Thanks in advance.

I have a function in VC++6. Could someone please help me how to access this function using DLLImport please. Please note that C++ unmanaged code doesn't have __declspec.

CAL32DLL_API long FAR PASCAL lGetNumber()
 return 102010;

Here's my C# Code:

public double GetNumber()




Hi, I am relatively new to c++ programming. I have always been a c# developer and worked on managed code only.

However I need to expose a method from a managed c++ class library(lets say helloworld() method) & use it from an unmanaged c++ code. If somebody can explain this with a simple example, that would be really great. I got to see this on other places also but I couldn't understand them.

The requirement is like this, because 70% of the code of the product is already written in unmanaged c++ code & I want to write my module in managed c++. So to make new module accessible from existing code I need this thing working.

Please suggest.

I need to write a .Net-Frontend for an unmanaged Windows DLL which contains an API that must not be changed. My frontend works perfectly with the 32-bit version of the DLL. I have trouble using the 64-bit version of the DLL, because some functions expect a void pointer and interpret it as a pointer into an integer array. I boiled the problem down to this simple function:

extern "C" int PASCAL EXPORT ExportedFunction(void *data)
    // Hier normaler Funktionsrumpf

    int *arr = (int *)data;

    return  sizeof(int);

Here is a stripped down version of my attempts to call "ExportedFunction":

Imports System.Runtime.InteropServices

Public Class Form1

    Declare Function ExportedFunction Lib "testlib.dll" (<MarshalAs(UnmanagedType.I4)> ByRef parameter As Integer) As Integer
    Declare Function ExportedFunction2 Lib "testlib.dll" Alias "ExportedFunction" (ByVal parameter() As Integer) As Integer

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim arr() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        Dim intsize As Integer = ExportedFunction(arr(6))
        Console.WriteLine("SizeOf int in DLL: " & intsize.ToString)
        Console.WriteLine("IntPtr size in .Net: " & IntPtr.Size.ToString)
    End Sub

    Sub PrintArray(ByVal arr() As Integer)
        For i As Integer = 0 To arr.Length - 1
            Console.Write(arr(i).ToString & " ")
    End Sub
End Class

In 32 bit, this produces the desired results:

SizeOf int in DLL: 4
IntPtr size in .Net: 4
1 2 3 4 5 6 8 9 10 10
2 3 4 4 5 6 8 9 10 10 

In 64 bit, this produces:

SizeOf int in DLL: 4
IntPtr size in .Net: 8
1 2 3 4 5 6 8 8 9 10
2 3 4 4 5 6 8 8 9 10 

Basically, my problem is that I can only pass the whole array to the function in 64 bit. Trying to write into the middle the array always writes to a single element.
Is there any way to get some kind of pointer into the array that I could pass to the DLL? Since the DLL requires fast data throughput, copying the array into a temporary array is not an option. I have already been experimenting with stuff like <MarshalAs(UnmanagedType.I4)>, but had no luck so far.

I could provide the full source code of the examples above, if that helps.



I have a C# program that at some point calls 2 functions from an unmanaged dll using p/invoke.  Everything works fine when I'm running in a console app.  When I compile the same program as a windows service and run it, it crashes.  The console app and service should be identical as far as my code is concerned... all either program does is create an object from another assembly of mine and run a Start() method on it.

I have used VS2010 to debug the managed and unmanaged code, and when I step through the Console app everything looks great.  When I attach the debugger to the service, i can step through the first function in the unmanaged code, control returns to the managed code, and then later when it comes to the point where it calls the second unmanaged function, the process terminates immediately before the debugger steps into the first line of unmanaged code.  There are no exceptions that I can see, and the only thing written to the event log is the generic "service terminated unexpectedly" message.  Running "sc query" on the command line lets me know the win32_exit_code is 1067.

Im running everything in .net 4, on winxp 32bit.  The serivce is running as Local System ideally, but the same behavior exists when I run it under my user account.  The second function call takes an IntPtr that comes from some locked bitmap data, in case that makes a difference.  Here is the DllImport attribute (remember this all works fine in the console app).  You might recognize that the function is from the Tesseract OCR project "tessdll".  I built the dll in VS2010 (building it in VS2005 and VS2008 had the same results).

[DllImport(tessdll, CallingConvention = CallingConvention.Cdecl)]
privatestaticexternint TessDllBeginPageUprightBPP(UInt32 xsize, UInt32 ysize, IntPtr buf, string lang, Byte bpp);

The first function which succeeds has this DllImport attribute:

[DllImport(tessdll, CallingConvention = CallingConvention.Cdecl)]
private static extern void SetWhitelist(string whitelist);

The actual function calls look like this:

SetWhitelist(whitelist); //<-- this succeeds
//some light processing tasks
TessDllBeginPageUprightBPP((uint)bmp.Width, (uint)bmp.Height, data.Scan0, language, bpp); //<-- crashes here

Any ideas what could be causing this or how to dig deeper?  All I can think of is that P/Invoking is somehow different when running a windows service.  If you'd like to suggest an alternative to Tesseract I could just forget the whole thing :).

Thanks for your help!


I have problem with calling function from exe files:

Lets assume, that i have Win32 Dll project with following code:

#include <windows.h>

extern "C" __declspec (dllexport) void TestFuncDll()
    MessageBox(NULL, "", "", 0);

and I have another win32 EXE project with following code:

#include <windows.h>

    return 1;

extern "C" __declspec (dllexport) void TestFuncExe()
    MessageBox(NULL, "", "", 0);

And finally I have C# project with some class with 2 imported functions:

public extern static void TestFuncDll();

public extern static void TestFuncExe();

And now, when i want to call TestFuncDll() everything works fine, but if I want call TestFuncExe() i have exeption: System.AccessViolationException. It occures on MessageBox function. If I dont use winapi functions, then everything works fine. Wats wrong?


I know Microsoft always gives some sort of backward compatibility to reuse previous written codes. So it is clear for me a normal scenario like this where a new

program written using NET Framework can call functionalities from an old native unmanaged dll.

The contrary, that is an old exe (MFC, Win32 ) using a new NET dll wrapped by a COM even though possible (I'm excluding an exe compiled with /clr option), in my opinion, works like a "forcing / breaking down".

However in the latter scenario you are loading a NET dll with its memory manager way  in the memory space of an unmanaged/native exe with its memory manager too (new, delete etc). And probably these two memory managers are different.

So my question:

in this last scenario is it safe/realiable use a NET dll loaded into the memory of a process written with native code?

Is there anyone who already did this scenario in production stage? if so is it working well?






I have the following scenario:

A C# application which refernce an assebly developed in C++/CLI The assembly wraps an unmanaged Dll In the code of the unmanaged Dll a make a LoadLibrary passing an .exe file as argument After the LoadLibrary (it successes) I make a call to LoadProcess to get the address of a function I call the function via its pointer

In this situation the call to the function loaded using LoadProcess make the application to crash. If the C# application is a commsole application I can see there's a not handled exception of type System.BadFormatImage. In a scenario where everything is unmanaged I don't get the crash. Further also in the mixed scenario if I make the LoadLibrary passing a .dll file everything works fine.

I'd like to understand if this is a bug or a limitation of the mixed enviroment.



Does code metrics in Visual Studiu 2008 Tema System  work for unmanaged C++ code?

I have a VB.Net app which uses ODBC 2 for its data access (odbc32.dll). It does SQLAllocConnect and SQLFreeConnect calls to connect and disconnect, but the second time it does the SQLAllocConnect it generates an AccessViolationException when running uner XP or Win Server 2003. Its fine under Win Server 2008 R2. My app relies on connecting to different databases so this functionality is vital. Any ideas? 


I am facing some issues in passing arguments from managed code to unmanaged code. I am having a C++ dll and i want to call few functions of it from a C# project (VS2010). C++ dll is not a native assembly or COM component. So i am using DllImport - P\Invoke.

C++ function details

typedef unsigned long UINT32;

typedef UNIT32 ABC_RESULT; // the return code from a ABC function

typedef UINT32 ABC_HOBJECT; // basic object handle

typedef ABC_HOBJECT ABC_HCONTEXT; // context object handle


ABC_RESULT Abc_Context_Create(

ABC_HCONTEXT* phContext  // out


phContext - Receives the handle to the created context object.


C# signature -

public class Abc1api


public static extern UInt32 Abc_Context_Create(UIntPtr phContext);


And i am calling it as below -

UInt32 result = 0;

UIntPtr hContext = new UIntPtr(sizeof(UInt32));

result = Abc1api.Abc_Context_Create(hContext);

I am able to build the project but while running i am getting below error -

A call to PInvoke function 'ABCTool!ABCTool.Abc1api::Abc_Context_Create' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

I tried IntPtr hContext instead of UIntPtr but result is same.

So i modified C# signature as mentioned below -

public class Abc1api


[return: MarshalAs(UnmanagedType.U4)]
public static extern UInt32 Abc_Context_Create([MarshalAs(UnmanagedType.U4), Out()] IntPtr phContext);


And i am calling it as below -

UInt32 result = 0;

IntPtr hContext = new IntPtr(sizeof(UInt32));

result = Abc1api.Abc_Context_Create(hContext);

When i run it, the error is - Cannot marshal 'parameter #1': Invalid managed/unmanaged type combination (Int/UInt must be paired with SysInt or SysUInt).

I tried UIntPtr but same result. Also tried allocating IntPtr hContext using Marshal i.e.

IntPtr hContext = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UInt32))); but getting same error as above.

I could not find out the reason of this error. Can any one help me in defining C# signature and how can i pass the arguments so that i can get the required hContext from unmanaged code and use it?

Thank you,




Recently our project migrated from Visual C++ 2003 to Visual C++ 2008. After conversion, the executables run without any issue under Windows XP, Windows 2003 (32-bit and 64-bit) and Windows 2008 (64-bit). But when running the same project under visual studio debugger, it works ok on Windows XP but doesnt work on Windows 2008 x64.

The failure occurs when making a call to an unmanaged DLL function.

CRevisionCheckApp *chk =

new CRevisionCheckApp();

hr_err = chk->versionCheck();

Here is the class declaration:











int versionCheck(void);


The exception is coming from tidtable.c:


__cdecl __set_flsgetvalue()





PFLS_GETVALUE_FUNCTION flsGetValue = FLS_GETVALUE; // Exception occurs here


if (!flsGetValue)


flsGetValue = _decode_pointer(gpFlsGetValue);

TlsSetValue(__getvalueindex, flsGetValue);



return flsGetValue;



/* _M_IX86 */


return NULL;



/* _M_IX86 */


The nature of exception is:

First-chance exception at 0x7575e124 in daq5.exe: 0xE0434F4D: 0xe0434f4d.

First-chance exception at 0x7575e124 in daq5.exe: 0xE0434F4D: 0xe0434f4d.

First-chance exception at 0x7575e124 in daq5.exe: 0xE0434F4D: 0xe0434f4d.

Unhandled exception at 0x7575e124 in daq5.exe: 0xE0434F4D: 0xe0434f4d.


Could someone please take a look and help me resolving this issue? I have submitted to this forum as this exception only occurs on Windows 2008 64-bit host while debugging. It works fine when not running under debugger.








I have a unmanaged dll using VC++ (VS 2008). It works fine when used from C# Windows Forms application. Now,
I want to use it from webservice which is calling a function from this Dll. It works fine on localhost, but when I publish &
upload it on Internet, it says "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. (Exception from HRESULT: 0x800736B1) "

I am unable to get it worked. Any answers to this ?



Dear All,

I would like to call an unmanaged C++ DLL into my C# application. I have read a lot of explanations but it always gave me errors.

It seems I cannot get the variable naming right. The C++ DLL has this function call:

        void GetData(unsigned char *A, unsigned long B, unsigned char C, unsigned char *D, int *E);

Can anyone help me how to properly call the function from C#:

        public static extern void GetData( ????? );


Any help will be very much appreciated.

Thank you very much.


In VS2010 I'm encountering a PInvokeStackImbalance error when I call an unmanaged C function that takes a string argument. This only happens in VS2010 (works fine in earlier versions of vs).  I know the MDA is more strict in VS2010 but I can't seem to figure out what the actual problem is.

The code in question can be reduced the following:

C Library:



__declspec(dllexport) int teststring(constchar *test)
  printf("str: %s \n",test);
  return 20;

VB App:

Declare Ansi Function teststring Lib "clib.dll" (ByVal s As String) As Integer

  Sub Main()
    Dim rc As Integer
    rc = teststring("Hello")
  End Sub

The call to teststring works but upon return the vs2010 MDA gives a PInvokeStackImbalance.

I tried adding explict marshalling information to the import declaration:

Declare Ansi Function teststring Lib "clib.dll" (<MarshalAs(UnmanagedType.LPStr)> ByVal s As String) As Integer
But that didn't work either (I tried LPStr, LPTStr, BStr).

How am I suppose to declare a call (in VB) to a C function that takes a string argument that works in VS2010?






Hi there,

I have a webservice that wraps an unmanaged C++ dll.  I'm wondering how I should handle state and multiple connections?  I'm thinking that the unmanaged dll will be shared across all connections...is this the case?  Note that I am using a shared host so I have limited abilities to modify IIS specifically.  If the unmanaged dll is not shared and will have a unique instance for every connection then I have nothing to worry about.  If it's the case it's shared then I guess I will have to persist the unmanaged state on a per-connection basis through a DB?


Craig Clayton


Hi all,

I call an unmanaged dll from my C# assembly using DllImport. So far this works just fine if both dlls are located in the same directory. Now I want to install the unmanaged dll into the WinSxS folder. But in order to use the unmanaged dll once it is installed there I need a manifest for my C# assembly that specifies the version of the unmanaged dll that shall be used.

I have seen how this works for C++ assemblies. All C++ assemblies that are compiled with Visual Studio 2005 / 2008 have an embedded manifest that specifies the C++ runtime (installed in the WinSxS folder) that shall be used. Such a manifest looks like this:

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level='asInvoker' uiAccess='false' />
      <assemblyIdentity type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />

Now it is not clear to me if I can do the same for C# assemblies. Visual Studio C++ projects offer a manifest by default in the project options. However, C# projects don't (as far as I know). I've tried mt.exe to embed the manifest into the C# assembly (have to embed it because the assembly shall be installed into the Global Assembly Cache) but somehow the unmanaged dll is not loaded from the WinSxS folder (system.dllnotfoundexception). I checked my managed dll using dependey walker and it does not show a reference to my unmanaged dll. This is different for C++ assemblies where I have seen references to unmanaged dlls.

Is it possible, can this approach work or do I have to write a managed C++ wrapper for my unmanaged dll?



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure