如何将IntPtr转换为SafeHandle?

时间:2017-04-13 09:48:26

标签: c# interop interopservices

我有C#Windows服务类:

class MyService : ServiceBase
{
    private void InitializeComponent() {
       //some other code ...
       SafeHandle sHandle = this.ServiceHandle; // I want to do this but this fails.
       SetServiceObjectSecurity(sHandle, secInfo, binaryDescriptor);
       //some more code ...
    }
}

如何将IntPtr(如this.ServiceHandle)转换为“System.Runtime.InteropServices.SafeHandle”?这样我就可以在函数调用“SetServiceObjectSecurity()”中使用它? 我的最终目标是给予服务管理员许可。

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用SafeHandle.SetHandle(IntPtr handle),如https://msdn.microsoft.com/de-de/library/system.runtime.interopservices.safehandle.sethandle(v=vs.110).aspx所述,看看它是否适合您?

编辑: 由于SafeHandle.SetHandle(IntPtr handle)是受保护的方法,因此您可以创建如下的派生类:

public class SafeHandleExtended : SafeHandle
{
    public void SetHandleExtended(IntPtr handle)
    {
        this.SetHandle(handle);
    }

    // .. SafeHandle's abstract methods etc. that you need to implement
}

虽然我没有测试这个是否正确,但我不知道这是否按你想要的方式工作。

相关问题