SafeHandle.SetOwnership(false)
-
I have a SafeHandle returned from an external function. I want to set the "ownsHandle" property to false, but the problem is that I'm only able to do this in the constructor. Is there a way to do it? Here is an example:
class MyHandle : SafeHandleZeroOrMinusOneIsInvalid {
MyHandle() : base(true) {}\[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)\] protected override bool ReleaseHandle() { externalReleaseHandle(handle); } \[DllImport("MyLib.dll")\] extern void externalReleaseHandle(IntPtr handle);
}
class MyClass {
public static void main(string[] args) {
MyHandle h1 = externalCreateHandle();
MyHandle h2 = externalGetPointer(h1);
}\[DllImport("MyLib.dll")\] extern void externalCreateHandle(); \[DllImport("MyLib.dll")\] extern void externalGetPointer(MyHandle handle);
}
The problem is that I want
h1
to be released, but noth2
. I thought about usingGC.SuppressFinalize(h2)
, but still callingDispose()
would cause the same problem. Is there a way to do this?Many thanks to all helpful guys here in CP! I really appreciate your help. :rose: My LinkedIn Profile
-
I have a SafeHandle returned from an external function. I want to set the "ownsHandle" property to false, but the problem is that I'm only able to do this in the constructor. Is there a way to do it? Here is an example:
class MyHandle : SafeHandleZeroOrMinusOneIsInvalid {
MyHandle() : base(true) {}\[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)\] protected override bool ReleaseHandle() { externalReleaseHandle(handle); } \[DllImport("MyLib.dll")\] extern void externalReleaseHandle(IntPtr handle);
}
class MyClass {
public static void main(string[] args) {
MyHandle h1 = externalCreateHandle();
MyHandle h2 = externalGetPointer(h1);
}\[DllImport("MyLib.dll")\] extern void externalCreateHandle(); \[DllImport("MyLib.dll")\] extern void externalGetPointer(MyHandle handle);
}
The problem is that I want
h1
to be released, but noth2
. I thought about usingGC.SuppressFinalize(h2)
, but still callingDispose()
would cause the same problem. Is there a way to do this?Many thanks to all helpful guys here in CP! I really appreciate your help. :rose: My LinkedIn Profile
Would
h2.DangerousAddRef()
(withoutDangerousRelease()
) suffice to achieve my objective?Many thanks to all helpful guys here in CP! I really appreciate your help. :rose: Know me better
-
Would
h2.DangerousAddRef()
(withoutDangerousRelease()
) suffice to achieve my objective?Many thanks to all helpful guys here in CP! I really appreciate your help. :rose: Know me better