我有以下问题:
public class ListenThread : SocketInvoke
{
[DllImport("Ws2_32", CharSet = CharSet.Auto)]
public unsafe static extern UInt32 WSAWaitForMultipleEvents(UInt32 cEvents, IntPtr hEventObject,
UInt32 fWaitAll, UInt32 dwTimeout, Boolean fAlertable);
public void ListenConnections(NetSharedData data)
{
while (true)
{
unsafe
{
if (WSAWaitForMultipleEvents((UInt32)1, data.signal, (UInt32)0, (UInt32)100, false) != WSA_WAIT_TIMEOUT)
{
}
}
}
}
data.signal是一个UInt32如何将它转换为IntPtr?我试试:
IntPtr signal = (IntPtr)data.signal;
但它不起作用,因为我需要一个指向data.signal(UInt32)类型的指针而不是作为指针的int值,这会产生内存异常。
我需要的C ++示例:
int signal = 0;
int* psignal = &signal;
答案 0 :(得分:2)
new IntPtr(data.signal);
您将在64位平台上遇到问题,因为data.signal仅挂在地址的低32位上。如果NetSharedData属于您,则应考虑将信号类型更改为IntPtr。
如果您正在尝试获取data.signal的地址:
new IntPtr(&data.signal);
我不确定这会正确固定对象(以防止内存管理器重新定位),我会做以下事情:
1)更改PInvoke签名:
public unsafe static extern UInt32 WSAWaitForMultipleEvents(UInt32 cEvents,
void* hEventObject, UInt32 fWaitAll, UInt32 dwTimeout, Boolean fAlertable);
2)使用fixed来固定对象
fixed (void* s = &data.signal)
{
if (WSAWaitForMultipleEvents((UInt32)1, s, (UInt32)0, (UInt32)100, false) != WSA_WAIT_TIMEOUT)
{
}
}
答案 1 :(得分:1)
这也编译
UInt32 unsignedInt = 6;
IntPtr iptr = new IntPtr(unsignedInt);
所以也许这就是你想要的
IntPtr signal = new IntPtr(data.signal);