Discussion:
passing int[] array to pointer to update the array
(too old to reply)
Kyu
16 years ago
Permalink
Hi, I am a newbie here.
I have a C dll and it has a function which updates pointer value.
It looks like
int Get_data (int num_points, int *real_data, int *imag_data)
{
...
return 0;
}

In C#, I tried to do following to pass an array of data as,

[DllImport("spinapi.dll")]
static extern int pb_get_data(int num_Points,
IntPtr realData,
IntPtr imagData);


unsafe public int Get_Data(int num_Points, ref int[] RealData, ref int
[] ImaginaryData)
{
int ret = 0;
unsafe
{
IntPtr ptr1 = Marshal.AllocHGlobal(RealData.Length);
IntPtr ptr2 = Marshal.AllocHGlobal
(ImaginaryData.Length);

Marshal.Copy(RealData, 0, ptr1, RealData.Length);
ret = pb_get_data(num_Points, ptr1, ptr2);
Marshal.FreeHGlobal(ptr1);
Marshal.FreeHGlobal(ptr2);
}
return ret;
}
But it just simply not working but crash. Could you help to solve this
problem?
Thanks,
Christian Fröschlin
16 years ago
Permalink
Post by Kyu
In C#, I tried to do following to pass an array of data as,
The approach looks reasonable, but you can't use "Length" directly
for the block size, try multiplying by 4 to get size in bytes.
Ben Voigt [C++ MVP]
16 years ago
Permalink
Post by Kyu
Hi, I am a newbie here.
I have a C dll and it has a function which updates pointer value.
It looks like
int Get_data (int num_points, int *real_data, int *imag_data)
{
...
return 0;
}
In C#, I tried to do following to pass an array of data as,
[DllImport("spinapi.dll")]
static extern int pb_get_data(int num_Points,
IntPtr realData,
IntPtr imagData);
Why don't you just use ref int parameters? .NET will pin the entire array
in place, and the C dll can then overwrite as much as needed. Just make
sure your array is big enough beforehand.
Post by Kyu
unsafe public int Get_Data(int num_Points, ref int[] RealData, ref int
[] ImaginaryData)
{
int ret = 0;
unsafe
{
IntPtr ptr1 = Marshal.AllocHGlobal(RealData.Length);
IntPtr ptr2 = Marshal.AllocHGlobal
(ImaginaryData.Length);
Marshal.Copy(RealData, 0, ptr1, RealData.Length);
ret = pb_get_data(num_Points, ptr1, ptr2);
Marshal.FreeHGlobal(ptr1);
Marshal.FreeHGlobal(ptr2);
}
return ret;
}
But it just simply not working but crash. Could you help to solve this
problem?
Thanks,
Loading...