6

我正在使用一些非托管代码,例如-

 [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
    //Creating a function that uses the API function...
    public static bool IsConnectedToInternet() {
        int Desc;
        return InternetGetConnectedState(out Desc, 0);
    }

关于在调用 Dispose 时如何处理/清理这个外部静态对象的任何建议?

4

3 回答 3

6

您认为是“外部静态对象”的东西根本不是对象,它只是编译器/运行时关于如何在 DLL 中查找函数的一组指令。

正如 Sander 所说,没有什么需要清理的。

于 2011-01-18T08:52:29.817 回答
3

You do not have any handles to unmanaged resources here. There is nothing to clean up.

于 2011-01-18T08:47:48.713 回答
2

这取决于您是否可以获得指针,例如

[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string principal, string authority, string password, LogonSessionType logonType, LogonProvider logonProvider, out IntPtr token);

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);

public void DoSomething() {
    IntPtr token = IntPtr.Zero;
    WindowsImpersonationContext user = null;
    try {
        bool loggedin = LogonUser((string)parameters[1], (string)parameters[2], (string)parameters[3], LogonSessionType.Interactive, LogonProvider.Default, out token);
        if (loggedin) {
            WindowsIdentity id = new WindowsIdentity(token);
            user = id.Impersonate();
        }
    } catch (Exception ex) {

    } finally {
        if (user != null) {
            user.Undo();
        }
        if (token != IntPtr.Zero) {
            CloseHandle(token);
        }
    }
}
于 2011-01-18T08:56:57.163 回答