C#

时间:2016-01-27 08:11:45

标签: c# pointers

我正在尝试一些关于C#Console项目中Heap和Pointer的内容(最初来自here)。我的程序看起来像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

public class Win32
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr malloc(int size);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int free(IntPtr region); //Change IntPtr befroe free method to int ---update---
}

public class Program
{
    public unsafe void Heap()
    {
        int* num1, num2, answer;
        num1 = Win32.malloc(sizeof(int));
        *num1 = 999; // 999 should be the value stored at where pointer num1 refers to

        num2 = Win32.malloc(sizeof(int));
        *num2 = 1; // 1 should be the value stored at where pointer num2 refers to

        answer = Win32.malloc(sizeof(int));
        *answer = *num1 + *num2; // 1000 should be the value of pointer answer's reference

        Console.WriteLine(*answer); // 1000?
        Win32.free(num1);
        Win32.free(num2);
        Win32.free(answer);
    }
}

调试后,收到错误消息说:

  

错误1无法将类型'System.IntPtr'隐式转换为'int *'。一个   存在显式转换(您是否错过了演员?)

error CS1502: The best overloaded method match for 'Win32.free(System.IntPtr)' has some invalid arguments

error CS1503: Argument 1: cannot convert from 'int*' to 'System.IntPtr'

我的问题是为什么我不能在malloc和free之前使用IntPtr,因为两个方法都返回void?我应该对我的代码做出哪些更改? 谢谢你的帮助。

--- ---更新

public static extern IntPtr free(int hWnd);更改为公开静态extern int free(IntPtr region);,将free(*num)更改为free(num)

给出额外的'CS1502'和'CS1503'两个错误。

---第二次更新--- C#自动处理堆事。 C#中没有malloc的等价物。这是一个死胡同。 T_T

1 个答案:

答案 0 :(得分:3)

一些错误:

在C / C ++中

void * malloc(int sizeToAllocate);
int free(void * region);

您将free返回的值传递给malloc。因此,您的导入应该是:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr malloc(int size); 

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int free(IntPtr region); 

因此你的解放代码应该成为:

 var num1Ptr = Win32.malloc(sizeof(int));
 int * num1 = (int*) num1Ptr.ToPointer();

 ...

 var num2Ptr = Win32.malloc(sizeof(int));
 int * num2 = (int*) num2Ptr.ToPointer();

 ...

 var answerPtr = Win32.malloc(sizeof(int));
 int * answer = (int*) answerPtr.ToPointer();

 ...

 Win32.free(num1Ptr);
 Win32.free(num2Ptr);
 Win32.free(answerPtr);