C#调用VC写的OCXVC的OCX中的一个函数的参数为指针类型,C#将其对应为了ref int
在C#中应该怎么传递数组给这个ref int型参数呢?————————————————————————————————————C# OCXref int
在C#中应该怎么传递数组给这个ref int型参数呢?————————————————————————————————————C# OCXref int
调试欢乐多
用int []buff中的buff作为参数之后,这样报错cannot convert from 'int[]' to 'ref int'
unsafe
{
fixed (int* pArray = array)
{
// callmethod(pArray)
}
}
C#将OCX中函数的指针参数直接对应成了ref int
这我也改不了~~~~~~~~~只能在C#这边想办法
对于pArray,报错说:cannot convert from 'int*' to 'ref int'
unsafe
{
int []buff = new int[size];
fixed (int *pArray = &buff[0])
{
int array = *pArray;
callmethod(ref array);
} }
IntPtr[] ptArray = new IntPtr[1];
ptArray[0] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * 65535);
IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)) * 1);
Marshal.Copy(ptArray, 0, pt, 1);
callmethod(ref pt); for (int i = 0; i < 65535; i++)
{
int n = (int)Marshal.PtrToStructure((IntPtr)((UInt32)ptArray[0] + i * sizeof(int)), typeof(int));
}
Marshal.FreeHGlobal(ptArray[0]);
Marshal.FreeHGlobal(pt);
这样写的话,这样报错:cannot convert from 'ref System.IntPtr' to 'ref int'
传递ref a[0]即可。
那请问如果要把结构数组的地址传递给ref int的话,该怎么解决
是自己定义的一个结构 [StructLayout(LayoutKind.Sequential)]
public struct THREGION //区域
{
public RECT rcBound; //区域边框
public byte iAttribute; //区域类型 RGNTYPE_xxx region type
public byte iField; //保留未使用
public byte nRecog_lang; //
}C#将OCX中的long*参数对应成了ref int型,这个是改不了的这样在C#中将结构体数组传递给ref int型
int size = Marshal.SizeOf(typeof(THREGION)) * nMaxRegionCount;
int[] buff = new int[size / 4 + 1];i = axWT_OCX.TH_Layout(0, nMaxRegionCount, ref buff[0], ref nRealRegionCount);
然后报错:尝试读取或写入受保护的内存。这通常指示其他内存已损坏。ref buff[0]用的不对吗?————————————————————————————————————
而你的错误是因为传递了错误的长度,那个nMaxRegionCount是结构体数组的长度,而不是buff数组的长度,这里必须传递buff数组的长度的长度,否则在写入该数组时就可能写到数组外面去了,最后那个那个nRealRegionCount则是返回你实际用到的长度。
Marshal.SizeOf(typeof(THREGION)) = 20nMaxRegionCount是结构体数组的大小,传过去之后,TH_Layout会再定义一个结构体数组,大小为nMaxRegionCount,函数的最后,会把新的结构体数组里面的内容复制到buff里面
-----------------------------------------------------------------------------
另外你想办法测试下C++里面封装的结构体大小,你这里是20,C++里面必须也是20呀。
嗯,OCX是另一位同事写的。我们商量一下,看能不能把参数给修改一下。总之,非常感谢你了。
http://blog.csdn.net/diaoying/article/details/8549964