How can I pass a pointer to an integer in C#

c, c#, interop, pinvoke

Solution

One option is simply to use C# pointer types - this requires `unsafe` block (or modifier on method/class), and compiling with `/unsafe`:

[DllImport(...)]
static extern int GetBuffer(byte* buffer, ref int maxSize);

Buffer can be allocated in several different ways. One would be to use a pinned heap array:

fixed (byte* buffer = new byte[4096])
{
    int maxSize = buffer.Length;
    GetBuffer(buffer, ref maxSize);
}

Another is to use `stackalloc`, though this is only feasible for small buffers:

byte* buffer = stackalloc byte[4096];
int maxSize = 4096;
GetBuffer(buffer, ref maxSize);

This particular approach is virtually identical to your C code in terms of performance and allocation patterns.

Another option altogether is to use marshaling for heap arrays, and avoid pointers entirely.

[DllImport(...)]
static extern int GetBuffer([Out] byte[] buffer, ref int maxSize);

byte[] buffer = new byte[4096];
int maxSize = buffer.Length;
GetBuffer(buffer, ref maxSize);

Problem

I have a C API with the signature: ``` int GetBuffer(char* buffer, int* maxSize) ``` In C, I will call it this way: ``` char buffer[4096]; int maxSize = 4096; GetBuffer(buffer, &maxSize); ``` maxSize is set to the buffer size, and set with the actual size filled. I need to call it from C#. How do I do that under "safe mode"?

Original source