这类似于以下SO问题:
cast-void-pointer-to-integer-array
c-pointers-pointing-to-an-array-of-fixed-size
然而,区别在于我想在C#中使用' unsafe'来实现这一点。我们可以使用指针的功能。
e.g。
以下代码适用于C:
int (*arr)[10] = (int (*)[10]) ptr;
其中' ptr'是无效指针。如何在C#中实现这一目标?
答案 0 :(得分:0)
我不完全确定这是你正在寻找的,但一个例子是这样的:
int[] items = new int[10];
unsafe
{
fixed ( int* pInt = &items[0] )
{
// At this point you can pass the pointer to other functions
// or read/write memory using it.
*pInt = 5;
}
}
当获取数组的地址时,您必须获取数组中第一项的地址 - 因此在上面的示例中为&items[0]
。
如果您将指针作为void*
函数参数接收,则必须将其强制转换为函数:
public static unsafe void F ( void* pMem )
{
int* pInt = (int*) pMem;
// Omitted checking the pointer here, etc. This is something
// you'd have to do in a real program.
*pInt = 1;
}
如果从外部源收到void*
,则必须知道通过指针可以安全访问多少字节(或整数等)。数据可能由特殊值(如终止0
或其他内容)分隔,或者您需要一个或多个字节/元素来通过指针安全地访问内存。
<强>更新强>
以下是调用在C:
中实现的非托管函数的示例// Function declaration in C
#define EXPORTFUNC __declspec(dllexport)
#define MYDLLAPI __declspec(nothrow) WINAPI
EXPORTFUNC int MYDLLAPI MyFunc1 ( byte* pData, int nDataByteCount );
// Import function in C#
[DllImport ( "My.dll" )]
private static extern int MyFunc1 ( byte* pData, int nDataByteCount );
// Call function with data (in unsafe class / method)
byte[] byData = GetData ( ... ); // returns byte array with data
fixed ( byte* pData = byData )
{
int nResult = MyFunc1 ( pData, byData.Length );
...
}
答案 1 :(得分:0)
你可以简单地把它投射到一个int*
指针..希望最好..显然:
// unsafe {}
var a = stackalloc int[5];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
a[4] = 5;
var v = (void*) a; // cast to void as example
for (var i = 0; i < 5; i++)
Console.WriteLine((*(int*)v)++); // back to int - 1, 2, 3, 4, 5
那说......你必须谨慎对待边界检查。 AFAIK没有允许边界的直接翻译。