tags:

views:

40

answers:

1

Here is a code sample

    [Guid("159463FB-A87A-4BBB-BCA1-064CD84495FB")]
    public interface ISettingsFactory
    {
        ISettings GetSettings(string userName);
    }

    [Guid("FD11B979-0ED1-41fb-8EB0-1234512345D0")]
    public interface ISettings
    {
        string PrivateKey {get;}
    }

    [Guid("782937826-705F-4be2-1234-A748332D6D1")]
    [ClassInterface(ClassInterfaceType.None)]
    public class SettingsFactory : ISettingsFactory
    {
        public ISettings GetSettings(string userName)
        {
            return new Settings(userName);
        }
    }

     [Guid("8BDC1F18-48FD-4a49-8DF3-D81C6321657B")]
     [ClassInterface(ClassInterfaceType.None)]
     public class Settings : ISettings
     {
         private readonly PrivateData privateData;

         public Settings(string userName)
         {
             privateData= PrivateData.Load(userName);
         }  

         public string PrivateKey 
         {
            get { return privateData.Key; }
         }
     }    

The problem is when creating SettingsFactory COM class from VB6 code and calling method GetSettings(userName)

settings = factory.GetSettings(userName);
key = settings.PrivateKey //<--- Exception occurs saying "Read write from protected memory is not allowed" or something like this.

The problem disappears when in GetSettings method I save Settings instance in field of SettingsFactory, so that GC doesn't collect it. Does anyone know why is this happening? I mean why GC collects objects that are exposed to COM? Isn't RCW increases the ref number on the Settings object after GetSettings get called?

A: 

I think the problems is that privateData.Key is not being marshalled correctly. I can't see the definition for the type of Key but my guess is it is a ptr to some kind of data and tha this data isn't being marshalled correctly. If thats the case you probably need to use one of the Marhal.PtrToXXX fumctions.

A great place to start if you want to learn more about using COM objects from .net are the MSDN articles on Runtime Callable Wrappers

Steve Sheldon