简体   繁体   English

如何在C#中实现malloc操作

[英]How to implement malloc operation in C#

float **ThreadID;
int Nthreads;

How to perform below task in C#? 如何在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. 如果在一个被调用的函数中使用这种语句,则可能需要添加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. 使用stackalloc,它将存储在堆栈中,并在离开函数时作为任何其他局部变量销毁。

ThreadID = stackalloc float*[Nthreads];

EDIT: As with all pointers in C#, you need to declare the unsafe context for your function, like 编辑:与C#中的所有指针一样,您需要声明函数的不安全上下文,例如

unsafe int doSomething(){
   ...
}
float[][] ThreadId;
int NThreads;

ThreadId = new float[Nthreads][];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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