I have a C# class library project (dll) with a single class, COMTest:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace COMTest
{
[Guid("45D639E4-FDDE-4b7b-A35F-FC19856DFF24")]
[ComVisible(true)]
public class Foo
{
public Foo()
{
Console.WriteLine("Constructing Foo");
}
private string mName = "FOO";
public string Name
{
get { return mName; }
set { mName = value; }
}
}
}
The project is registered for COM interop, and the assembly is COM-visible. The target framework is .Net 3.5, and the platform target is x86. The .dll is registered using the 32-bit C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe /codebase COMTest.dll
I am attempting to access this class from VBScript (again, 32-bit, using C:\Windows\SysWOW64\cscript.exe test.vbs), but I appear to be having problems acquiring an instance of Foo within the script. I can use the class; I just can’t keep any reference to it.
Here is my script:
Wscript.Echo "CreateObject(""ComTest.Foo"").Name Results: " + CreateObject("COMTest.Foo").Name
IF IsEmpty(CreateObject("COMTest.Foo")) THEN Wscript.Echo "CreateObject() is empty" ELSE Wscript.Echo "CreateObject() is NOT empty"
DIM foo : CreateObject("COMTest.Foo")
IF IsEmpty(foo) THEN Wscript.Echo "foo is empty" ELSE Wscript.Echo "foo is NOT empty"
And here is the output:
Constructing Foo
CreateObject("ComTest.Foo").Name Results: FOO
Constructing Foo
CreateObject() is NOT empty
Constructing Foo
foo is empty
As you can see, the CreateObject() call succeeds–I’m just unable to keep a reference to the object returned (in foo).
I feel like I’m missing something simple. How do I retain the object returned from CreateObject()?
The colon you use in line three doesn’t actually do anything, it just separates two different statements. Your
Dim foo : CreateObject("COMTest.Foo")is equivalent to:Which creates the object but doesn’t actually set its reference to any variable. I would write it like this: