views:

183

answers:

2

Hello,

I have the following problem. I have a C++ dll, containing the function

void cpp_send (void *data_, size_t size_, free_fn *ffn_)
{
    //sends data
}

then I have C# dll that has a class

public class CS_dll : IDisposable
{
    void cs_send (void *data)
   {
       IntPtr ptr = Marshal.AllocHGlobal (data.Length);
       Marshal.Copy (data, 0, ptr, data.Length);
       try
       {
            cpp_send (ptr,
            Convert.ToUInt32 (data.Length), Free);
       }
 catch
 {
     Free (ptr);
 }
}

//The function Free () looks like:

public static void Free (IntPtr ptr)
{
    Marshal.FreeHGlobal (ptr);
}

I call it from C# aplication as

CS_dll w = new CS_dll();
byte [] msg = new byte [msg_size];
w.cs_send (msg, msg_size);

The problem is, that after some time, the C# aplication crashes with SystemAccessViolationExcetpion. Do you have any idea where the problem is?

To make it clearer: The C# aaplication can finish for some types of input while for the others it crashes, so I dont thing there is problem with calling convention, is there?

A: 

What is 'data.Length' ? Please provide the defition where data is declared.

UPDATE: It could also be the callback (delegate) you are passing into the function is using the stdcall, while the unmanaged function is expecting a cdecl calling convention.

leppie
+1  A: 

You are sending 5 parameters to a function that receives only 3?

Edit: Thanks for fixing the code. You say it fails with some types of data. Can you say which type?

gbianchi
it depends on how many messages I try to send, it crashes with about 100000, but works fine for all bellow.
Maybe the C++ process can't allocate a pointer for so many quantity of data? Did it worked by itself?
gbianchi