473,387 Members | 1,464 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Dynamically create COM objects in C#

Ray
I want to dynamically load DLLs (created from VB) and instantiate a
class with a particular name, like "ProcessClass".

I am able to load the DLL and confirm there is a class by that name BUT
I can't seem to create it or call methods to this newly created
instance. I have the following code:

public class Script
{
[DllImport("oleaut32", CharSet=CharSet.Unicode)]
private extern static void LoadTypeLib(string dllFilePath, out
UCOMITypeLib typeLibrary);

UCOMITypeLib typeLibrary;
LoadTypeLib(dllName, out typeLibrary);

for (int i = 0; i < typeLibrary.GetTypeInfoCount(); i++)
{
typeLibrary.GetDocumentation(i, out typeName, out
typeDocumentation, out typeHelpContext, out typeHelpFile);
if (typeName == "ProcessClass")
{
UCOMITypeInfo typeInformation;
object classInstance;

typeLibrary.GetTypeInfo(i, out typeInformation);
typeInformation.CreateInstance(null, ref guidIUnknown, out
classInstance);

MethodInfo method = classType.GetMethod("DoSomething",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public
);
method.Invoke(classInstance, new object[0]);
}
}
}

Am I going down the wrong road? The class seems to be created without
exception, but the created instance doesn't seem to be bound properly
as I don't see any of the methods I'm looking for when I loop through!!

-Ray

Nov 17 '05 #1
4 16986
Ray,

First, you don't need to use interop and everything you are doing to
create an instance of your COM class. You can easily do this:

// Get the type of the COM object.
// I used Project as the dll name, because COM objects usually have a
two-part program id.
Type comType = Type.GetTypeFromProgID("Project.ProcessClass");

// Create an instance.
object instance = Activator.CreateObject(comType);

At that point, you have the instance of your object. You will need to
use reflection in order to make calls to the object.

In order to get around this, you should define an interface that
reflects the interface on the object you want to call. Since COM is an
interface-based system (even when VB is involved, which obfuscates that
fact), you can always get that interface and then have an early-bound
reference in your system.

The problem with this is that if you didn't originally define the
interface separately from the class in your project, then you will have to
use TLBIMP to get the definition, and not use the early bound types that are
defined for you.

Of course, if you only need this class in this dll, then why not just
set a reference to it directly?

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Ray" <ra********@email.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
I want to dynamically load DLLs (created from VB) and instantiate a
class with a particular name, like "ProcessClass".

I am able to load the DLL and confirm there is a class by that name BUT
I can't seem to create it or call methods to this newly created
instance. I have the following code:

public class Script
{
[DllImport("oleaut32", CharSet=CharSet.Unicode)]
private extern static void LoadTypeLib(string dllFilePath, out
UCOMITypeLib typeLibrary);

UCOMITypeLib typeLibrary;
LoadTypeLib(dllName, out typeLibrary);

for (int i = 0; i < typeLibrary.GetTypeInfoCount(); i++)
{
typeLibrary.GetDocumentation(i, out typeName, out
typeDocumentation, out typeHelpContext, out typeHelpFile);
if (typeName == "ProcessClass")
{
UCOMITypeInfo typeInformation;
object classInstance;

typeLibrary.GetTypeInfo(i, out typeInformation);
typeInformation.CreateInstance(null, ref guidIUnknown, out
classInstance);

MethodInfo method = classType.GetMethod("DoSomething",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public
);
method.Invoke(classInstance, new object[0]);
}
}
}

Am I going down the wrong road? The class seems to be created without
exception, but the created instance doesn't seem to be bound properly
as I don't see any of the methods I'm looking for when I loop through!!

-Ray

Nov 17 '05 #2
Ray
Thanks Nicholas, I'm trying out your suggestion.

After I created the instance, I added the following:

MethodInfo method = comType.GetMethod("ProcessActive");
object result = method.Invoke(instance, new object[0]);

BUT GetMethod() returns null, and I know for sure the ProcessActive
exists. Do I need to create an ObjRef to get access to the actual
methods, because right now the only methods I'm getting are:
Method name: CreateObjRef
Method name: InitializeLifetimeService
Method name: GetLifetimeService
Method name: GetHashCode
Method name: Equals
Method name: ToString
Method name: GetType

-Ray

Nov 17 '05 #3
Ray,

The reason for this is because the type you get doesn't actually have
any members on it. The members you see are for the __ComObject type which
represents a COM object that is being used in interop. If you call the
InvokeMember method, passing the name of the member (as well as the correct
binding flags), it will work. Reflection knows enough to call through COM
(through the IDispatch implementation actually) to make the call to your
object.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"Ray" <ra********@email.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Thanks Nicholas, I'm trying out your suggestion.

After I created the instance, I added the following:

MethodInfo method = comType.GetMethod("ProcessActive");
object result = method.Invoke(instance, new object[0]);

BUT GetMethod() returns null, and I know for sure the ProcessActive
exists. Do I need to create an ObjRef to get access to the actual
methods, because right now the only methods I'm getting are:
Method name: CreateObjRef
Method name: InitializeLifetimeService
Method name: GetLifetimeService
Method name: GetHashCode
Method name: Equals
Method name: ToString
Method name: GetType

-Ray

Nov 17 '05 #4
Ray
Thanks a lot for your help. I ended up with the following code for
those who are interested. As opposed to create the instance with the
ProgID, I had to create it with CLSID as I couldn't find an easy way to
retrieve the project name (in my case, not the same as the DLL name).

Type comType = Type.GetTypeFromCLSID(someClassID);
object comInstance = Activator.CreateInstance(comType);
comType.InvokeMember(someMethodName, BindingFlags.InvokeMethod |
BindingFlags.IgnoreReturn | BindingFlags.Public, null, comInstance, new
object[0]);

The code is now very simple.

Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: vertigo | last post by:
Hello I need to create some objects durring program execution - but it's names are dynamically generated (depends on parameters). How can i do it ? Thanx Michal
9
by: Patrick.O.Ige | last post by:
I have a code below and its a PIE & BAR CHART. The values now are all static but I want to be able to pull the values from a database. Can you guys give me some ideas to do this? Thanks ...
2
by: -BA- | last post by:
Hi! I wonder if it is possible to dynamically name a object (e.g. checkbox, combox etc.) during runtime. I know I can create a object during runtime like this: Me.MyLabel = New Label...
9
by: sashang | last post by:
Hi I'd like to use metaclasses to dynamically generate a class based on a parameter to the objects init function. For example: class MetaThing(type): def __init__(cls, name, bases, dict,...
7
by: Ron Goral | last post by:
Hello I am new to creating objects in javascript, so please no flames about my coding style. =) I am trying to create an object that will represent a "div" element as a menu. I have written...
12
by: vbnewbie | last post by:
I am having problems accessing properties of dynamically generated objects in VB2005. Can someone please help? In a nutshell: My app creates an equal number of checkboxes and labels that share the...
6
by: RSH | last post by:
Hi, i have a situation where I need to dynamically create objects in a loop. My question surrounds intantiation naming in such a scenerio. Below is a snippet that is basically hardcoding each...
10
by: Jess | last post by:
Hello, I have a program that stores dynamically created objects into a vector. #include<iostream> #include<vector> using namespace std;
1
by: krishna81m | last post by:
I am unable to create a list of objects dynamically. I run a SQL query on the database and populate objects of types that I also know aprior. I read the query as a string, run it on the database and...
29
by: Quarco | last post by:
This one is driving me nuts.... var tbl = document.createElement("table"); var tbody = document.createElement("tbody"); for(var i=0; i<10; i++) { var row =...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.