Your basic problem is, that you are intending to change the a variable you pass by value.
That having said, as Matthew Watson pointed out in the comment to your question, you have to adjust the interface of the method you are calling in the DLL to take a pointer pointing to the location of the pointer you want to modify.
In your example you need to pass the pointer to managedHandle
to ReleaseHandle
.
Hence your code should look like this in your DLL:
void ReleaseHandle(void** handle) {
*handle = nullptr; /* Note that here we dereference one level
to modify the content of the location
pointed at */
}
In your C# program on the other hand, you should import the function with something like that:
[DllImport("YourLibrary.dll")]
static extern void ReleaseHandle(ref IntPtr handle);
and invoke it by using the ref
keyword:
IntPtr value = IntPtr.Add(IntPtr.Zero, 123456789);
ReleaseHandle(ref managedHandle);
Console.WriteLine(managedHandle); // this outputs to 0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…