当我们实现的COM对象,或者ActiveX控件在浏览器中调用的时候,往往会出现警告框,提示不安全的控件正在运行。这是因为浏览器安全策略所限定的,浏览器认为只有“安全的对象”才能够被执行。所谓安全的对象就是指那些不访问本地资源的对象,例如不会去读注册表,不会写文件等等。一个满足条件的对象通过支持IObjectSafety接口告诉浏览器,自己是合法的。下面就简单的介绍一下怎么在C#中实现对于IObjectSafety接口的支持。 思路C[
object,
uuid(CB5BDC81-93C1-11cf-8F20-00805F2CD064),
pointer_default(unique)
]
interface IObjectSafety : IUnknown
{
HRESULT GetInterfaceSafetyOptions(
[in] REFIID riid, // Interface that we want options for
[out] DWORD * pdwSupportedOptions, // Options meaningful on this interface
[out] DWORD * pdwEnabledOptions); // current option values on this interface HRESULT SetInterfaceSafetyOptions(
[in] REFIID riid, // Interface to set options for
[in] DWORD dwOptionSetMask, // Options to change
[in] DWORD dwEnabledOptions); // New option values
} [Guid("CB5BDC81-93C1-11cf-8F20-00805F2CD064")]
public interface IObjectSafety
{
// methods
unsafe void GetInterfacceSafyOptions(
System.Int32 riid,
System.Int32* pdwSupportedOptions,
System.Int32* pdwEnabledOptions);
void SetInterfaceSafetyOptions(
System.Int32 riid,
System.Int32 dwOptionsSetMask,
System.Int32 dwEnabledOptions);
}
继承 public class MyControl : System.Windows.Forms.UserControl,IObjectSafety // implement functions of IObjectSafety
public unsafevoid GetInterfacceSafyOptions(System.Int32 riid,System.Int32
{
{out这个参数修饰符解决。 [Guid("CB5BDC81-93C1-11cf-8F20-00805F2CD064")]
public interface IObjectSafety
{
// methods
void GetInterfacceSafyOptions(
System.Int32 riid,
out System.Int32 pdwSupportedOptions,
out System.Int32 pdwEnabledOptions);
void SetInterfaceSafetyOptions(
System.Int32 riid,
System.Int32 dwOptionsSetMask,
System.Int32 dwEnabledOptions);
}
// implement functions of IObjectSafety
public unsafevoid GetInterfacceSafyOptions(System.Int32 riid,outSystem.Int32 pdwSupportedOptions,outSystem.Int32 pdwEnabledOptions)
{
{InterfaceTypeAttribute,就是用来说明定义的接口是从IUnknown继承还是IDispatch继承,缺省情况下是Dual的,所以是两份。 [Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IObjectSafety
{
// methods
void GetInterfacceSafyOptions(
System.Int32 riid,
out System.Int32 pdwSupportedOptions,
out System.Int32 pdwEnabledOptions);
void SetInterfaceSafetyOptions(
System.Int32 riid,
System.Int32 dwOptionsSetMask,
System.Int32 dwEnabledOptions);
}
其余代码不变,重新编译,通过;察看导出类型库,果然少了很多垃圾;调用测试页面,正确。激动中...当然我们可以写一个对象读写本地文件,但是支持IObjectSafety接口,并且始终声明自己是合法的,这样来欺骗浏览器,那么代码就很简单了,如下: // implement functions of IObjectSafety
public void GetInterfacceSafyOptions(System.Int32 riid,out System.Int32 pdwSupportedOptions,out System.Int32 pdwEnabledOptions)
{
pdwSupportedOptions = CLsObjectSafety.INTERFACESAFE_FOR_UNTRUSTED_CALLER;
pdwEnabledOptions = CLsObjectSafety.INTERFACESAFE_FOR_UNTRUSTED_DATA;
}
public void SetInterfaceSafetyOptions(System.Int32 riid,System.Int32 dwOptionsSetMask,System.Int32 dwEnabledOptions)
{
}
参考文档1、HOWTO: Implement IObjectSafety in Visual Basic Controls