我是一个c++开发者,现在一个项目需要用c sharp,刚开始学习c sharp。问题如下,
public delegate uint EdsPropertyEventHandler(uint inEvent, uint inPropertyID, uint inParam, IntPtr inContext); 在上面这个委托中,最后一个参数是IntPtr,但是我现在希望能够像c++那样能够传递this给IntPtr,然后在这个委托函数中调用this的函数。1、这样是否可行?2、我觉得我对IntPtr理解不清楚的,那位可以解释哈?3、如果这种方法不行,我可以通过什么方式来实现我要功能(注意那个委托是一个lib中的函数,我没法去修改)。
public delegate uint EdsPropertyEventHandler(uint inEvent, uint inPropertyID, uint inParam, IntPtr inContext); 在上面这个委托中,最后一个参数是IntPtr,但是我现在希望能够像c++那样能够传递this给IntPtr,然后在这个委托函数中调用this的函数。1、这样是否可行?2、我觉得我对IntPtr理解不清楚的,那位可以解释哈?3、如果这种方法不行,我可以通过什么方式来实现我要功能(注意那个委托是一个lib中的函数,我没法去修改)。
(IntPtr)this.Handle
2. IntPtr 就是一个 pointer
强制转
不过成功率应该不高, C++ 的 class 和 C# 的class 是不同的
在C#类上添加[CLSCompliant(true)]
上面的方法有点诡异,不习惯的话就在C#下用非安全(unsafe)代码好了,非安全代码中可以使用指针
----------------------
既然Lib里面写的参数类型是IntPtr,那么Lib的作者初衷肯定不是让你传递this,而是本机资源,如某个窗体的句柄
而sender一般为调用方。也就是LZ所谓的thisLZ的是要做什么,是在C#中使用非托管的lib吗?
但是不明白为什么要传this过去,而this里面的东西是未知的(调用方与实现方互相不知道里面有什么东西)。
{
public static void Main()
{
TextWriter tw = System.Console.Out;
GCHandle gch = GCHandle.Alloc( tw );
CallBack cewp = new CallBack( CaptureEnumWindowsProc );
// Platform invoke prevents the delegate from being garbage
// collected before the call ends.
LibWrap.EnumWindows( cewp, (IntPtr)gch );
gch.Free();
}
private static bool CaptureEnumWindowsProc( int handle, IntPtr param )
{
GCHandle gch = (GCHandle)param;
TextWriter tw = (TextWriter)gch.Target;
tw.WriteLine( handle );
return true;
}
}在这里把一个TextWriter类转换为IntPtr