简体   繁体   中英

How to implement malloc operation in C#

float **ThreadID;
int Nthreads;

How to perform below task in C#?

ThreadID = (float **)malloc( Nthreads* sizeof(float *) );

Is there any reason why you need unmanaged memory for your application? Otherwise the normal way to do it would be

ThreadID = new float*[Nthreads];

That will allocate a new Array for you. If you use this kind of statement in a function that is called a lot, you might want to add the stackalloc-keyword. otherwise slow garbage collection could leed to increased memory consumption. With stackalloc it will be stored on the stack and destroyed as any other local variable upon leaving the function.

ThreadID = stackalloc float*[Nthreads];

EDIT: As with all pointers in C#, you need to declare the unsafe context for your function, like

unsafe int doSomething(){
   ...
}

You can try with

Marshal.AllocHGlobal 

You have detail on msdn

http://msdn.microsoft.com/fr-fr/library/system.runtime.interopservices.marshal.allochglobal.aspx

float[][] ThreadId;
int NThreads;

ThreadId = new float[Nthreads][];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM