0

I have one C DLL which I am using into C# code (.net 4.0) When I access the C method, it raises below exception

System.AccessViolationException {"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."}

Here I am giving you details of C code as well as C# code

C Code:

__declspec(dllexport) int SampleFunction(int **p_StackIndexes)
{
    printf("value1: %d: ", p_StackIndexes[0][0]);
    return 1;
}

C# Code

[DllImport(@"cpp.dll", CallingConvention = CallingConvention.Cdecl)]
unsafe private static extern UInt16 SampleFunction(
    out int[,] p_StackIndexes
);

unsafe static void Main(string[] args)
{
    unsafe
    {
        int[,] p_StackIndexes = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
        int x = SampleFunction(out p_StackIndexes);  //This line raises said exception
    }
}

I have tried all CallingConvention like StdCall, Cdecl, Winapi but this does not work in any case.

What's wrong in my code ? Please note that my basic requirement is to use output parameter so basically I will be assigning some values to output parameter in C code and then access it from C# code.

If you can provide any sample code then it will be of good help.

Thanks, Kiran

Kiran
  • 1
  • 4
  • You will first need to write correct C code. Your array handling is broken, what you have doesn't work in a C program either. Trying to pinvoke it doesn't make it better, it just makes it harder to debug. – Hans Passant Apr 17 '13 at 12:57
  • @Hans - Thanks for the reply Yes, I am not much experienced in C. but now I have to use C DLL in my C# application. Can you please give me some sample code which updates output parameters in C ? – Kiran Apr 18 '13 at 05:32

0 Answers0