IntPtr问题

时间:2023-03-08 18:27:30
IntPtr问题

public aaa(IntPtr myPtr,int left, int top, int width, short height)

这里myPtr应该是对应到一块内存,你需要查看aaa函数是如何把myPtr转化成它内部要使用的结构体的(一般都是结构体,也可能是其它对象,比如数组)。

然后,你需要在你的托管代码中,定义该结构体,使用StructLayout特性,对结构体的字段使用MarshalAs特性,类似这样:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Size = 13)]
public struct A101220Output
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]
public string TransactionAccountID; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)]
public string IsAuthenticated;
}

然后在需要使用的地方,获取该结构体对象的IntPtr,如下:
//创建托管对象
A101220Output output = new A101220Output ();
output.TransactionAccountID = "11000000841";
output.IsAutienticated = "false"; //分配非托管内存,并获取非托管内存地址起始位置指针
int size = Marshal.SizeOf(output);
IntPtr buffer = Marshal.AllocHGlobal(size); try
{
//将托管对象拷贝到非托管内存
Marshal.StructureToPtr(output, buffer, false); //调用非托管方法
aaa.(buffer,0,0,640,480);
}
finaly
{
//释放非托管内存
Marshal.FreeHGlobal(buffer);
}