C# は IntPtr を使用して、外部に割り当てられたメモリを表します。C# のポインターと参照は、ガベージ コレクターによって提供されるメモリでのみ使用できます。
System.InteropServices.Marshal クラスは、IntPtr によって表されるネイティブ メモリ領域とやり取りするためのいくつかのメソッドを提供しますが、もちろんそれらはタイプ セーフではありません。
しかし、あなたの関数には、割り当てられたメモリへのポインターを返す可能性のあるものは何もありません。ダブルポインター引数またはポインター戻り値が必要ですが、どちらもありません。
編集して、要求に応じて例を追加します。
// this doesn't work right
void external_alloc_and_fill(int n, int* result)
{
result = new int[n];
while (n-- > 0) { result[n] = n; }
}
extern external_alloc_and_fill(int n, int* result)
int a = 5;
fixed (int* p = &a) {
external_alloc_and_fill(17, p);
// p still points to a, a is still 5
}
より良い:
// works fine
void external_alloc_and_fill2(int n, int** presult)
{
int* result = *presult = new int[n];
while (n-- > 0) { result[n] = n; }
}
extern external_alloc_and_fill2(int n, ref IntPtr result)
int a 5;
IntPtr p = &a;
external_alloc_and_fill2(17, ref p);
// a is still 5 but p is now pointing to the memory created by 'new'
// you'll have to use Marshal.Copy to read it though