سؤال

For different purposes I need to provide an interface that implementents the following functions in C#

  • malloc
  • calloc
  • realloc
  • free

But I would prefer to not to code it myself (why reinvent the wheel). A better solution would be when my alloc-functions was called, I would simplely call the alloc-functions in stdlib.h, the interface is made so I "just" need to call those functions.

The question is, how do I access the functions in the stdlib.h from C#? I know about platform invoke, and I am getting better at it. But for platform invoke to work, I need a .dll And I don't know which .dll implements the stdlib.h

هل كانت مفيدة؟

المحلول

I don't think this sounds like the best solution for your problem. But to answer the question you first need to decide which C runtime to use. One possibility is the system component in msvcrt.dll. Access the functions like this:

[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr malloc(IntPtr size);

[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern void free(IntPtr ptr);

[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr calloc(IntPtr num, IntPtr size);

[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr realloc(IntPtr ptr, IntPtr size);

However, the official position from MS is that msvcrt.dll is private and not for use by third party applications. So you might prefer to link to a C++ runtime associated with a specific version of MSVC. For example, to link to the VS2013 runtime specify msvcr120.dll. This of course would require you to distribute that runtime.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top