你要代码吧?不过在类中使用指针是多余的,一个引用类型的字段本身存放的就是首地址。struct中使用还有些许意义。 unsafe class TestClass { public int* A; public TestClass(int[] b) { fixed(int* p = b) { A = p; } } } class Program { unsafe static void Main(string[] args) { int[] x = new int[10]; TestClass tc = new TestClass(x); *(tc.A + 1) = 255; Console.ReadLine(); } }
[StructLayout(LayoutKind.Sequential)] class TestClass { public byte[] a = new byte[1024 * 1024]; } class Program { static void Main(string[] args) { TestClass tc = new TestClass(); Console.WriteLine(Marshal.SizeOf(tc)); Console.ReadLine(); } }运行一下这个,这个包含1M数组的类实例,大小是4个字节。因为字段a本身存放的就是数组首地址,所以你定义成指针也没什么意义,直接定义数组类型就可以。“内存溢出和虚拟内存太低”不是c#的原因,是过程存在问题。你以c++指针的思维去理解c#的引用类型,以c++的new理解c#的new,唯一区别就是c++可以手动delete,c#要靠GC,如果问题发生在GC,不妨尝试Marshal类分配和释放内存或者直接调用windows api。
没人来了?在类中定义一个数组的指针字段 unsafe public double* resultGradient = new double[CallDLL.width * CallDLL.height * 3]; 这样做是不是不行?因为编译器报错:右边的初始化和左边的double*不匹配。
{
public int* A;
public TestClass(int[] b)
{
fixed(int* p = b)
{
A = p;
}
}
}
class Program
{
unsafe static void Main(string[] args)
{
int[] x = new int[10];
TestClass tc = new TestClass(x);
*(tc.A + 1) = 255;
Console.ReadLine();
}
}
[StructLayout(LayoutKind.Sequential)]
class TestClass
{
public byte[] a = new byte[1024 * 1024];
}
class Program
{
static void Main(string[] args)
{
TestClass tc = new TestClass();
Console.WriteLine(Marshal.SizeOf(tc));
Console.ReadLine();
}
}运行一下这个,这个包含1M数组的类实例,大小是4个字节。因为字段a本身存放的就是数组首地址,所以你定义成指针也没什么意义,直接定义数组类型就可以。“内存溢出和虚拟内存太低”不是c#的原因,是过程存在问题。你以c++指针的思维去理解c#的引用类型,以c++的new理解c#的new,唯一区别就是c++可以手动delete,c#要靠GC,如果问题发生在GC,不妨尝试Marshal类分配和释放内存或者直接调用windows api。