Search code examples
c#marshallingdllimportintptr

Marshal.Copy not copying over value


I'm not very familiar with C# and I'm trying to use 'Marshal.Copy' but it's not changing the value of the IntPtr that I'm using.

IntPtr ptr = InitPointer(width, height);

Marshal.Copy(inputIntArray, 0, ptr, width * height * 4);

Where InitPointer is defined as:

[DllImport(@"../../../../Debug/KernelApplier.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr InitPointer(int x, int y);

And in my kerneApplier.dll the function is written as:

int * inputBuffer;
int size;
int m_x, m_y;

extern "C" __declspec(dllexport) int* InitPointer(int x, int y) {
    size = x*y * sizeof(cl_int3);
    m_x = x;
    m_y = y;
    inputBuffer = (int*)malloc(size * sizeof(int));
    return inputBuffer;
}

I'm using my watch window to monitor the values where:

  • ptr.m_value = 0x0641c040
  • inputIntArray[0] = 152
  • 0x0641c040 = 104972352 //This does not change after the Marshal.Copy

Am I using Marshal.copy incorrectly or is there a problem passing the data from C++ to C#


Solution

  • Your code is fine. The IntPtr value does not change, but it's the address of the unmanaged memory so it is not expected to change.