C#调用C语言的API时一般把void *指针转换成IntPtr,但这经常远远不够的。在C语言中void *是个万金油,尤其是一些老的c语言程序,所有的参数就一个void*指针,里面包罗万象,然后在程序中来一个switch,甚至多个switch来处理不同的参数。最近笔者就碰到了这个问题,不得不来研究一下怎么把void *指针转换成IntPtr。
1.void *指针到IntPtr的简单转化。
c语言函数原型:
int SetConfig(int type, void *p);
这里假设p的所传递的参数式是结构体A:
struct A
{
wchar_t osdbuffer[100];
unsigned short ix;
unsigned short iy;
};
那么在C#中原型可以定义如下:
int SetConfig(int type, IntPtr p);
结构体A
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct A {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string osdbuffer;
public ushort ix; //显示坐标x
public ushort iy;