pointers - Type conversion issue in C# -
i'm trying (originally comes here) heap , pointer on c# console project. , program looks this:
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 int ---update--- } public class program { public unsafe void heap() { int* num1, num2, answer; num1 = win32.malloc(sizeof(int)); *num1 = 999; // 999 should value stored @ pointer num1 refers num2 = win32.malloc(sizeof(int)); *num2 = 1; // 1 should value stored @ pointer num2 refers answer = win32.malloc(sizeof(int)); *answer = *num1 + *num2; // 1000 should value of pointer answer's reference console.writeline(*answer); // 1000? win32.free(num1); win32.free(num2); win32.free(answer); } }
after debugging, got error message says:
error 1 cannot implicitly convert type 'system.intptr' 'int*'. explicit conversion exists (are missing cast?)
error cs1502: best overloaded method match 'win32.free(system.intptr)' has invalid arguments error cs1503: argument 1: cannot convert 'int*' 'system.intptr'
my questions here why can't use intptr before malloc , free, since both method return void? changes should make on codes? thank help.
---update---
change: public static extern intptr free(int hwnd);
public static extern int free(intptr region);
, free(*num)
free(num)
gives 'cs1502' , 'cs1503' 2 errors.
---second update--- c# deal heap thing automatically. there no equivalent of malloc in c#. it's dead end. t_t
a few mistakes:
in c/c++
void * malloc(int sizetoallocate); int free(void * region);
you pass free
value returned malloc
. imports should be:
[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);
and consequently freeing code should become:
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);
Comments
Post a Comment