473,772 Members | 2,448 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamically instantiate a class

Hi All,

My application reads a 'Class' name (as a string) from a file at Run time.
Can i create an instance this Class ?

Thanks
Sumit
Jul 22 '05 #1
11 2494

"Sumit Nagpal" <su***@noida.at renta.com> wrote in message
news:2t******** *****@uni-berlin.de...
Hi All,

My application reads a 'Class' name (as a string) from a file at Run time.
Can i create an instance this Class ?


Sure.

std::string classname;
std::ifstream instream("myfil e");
instream >> classname;
myClass *mc = 0;

if(classname == "myClass")
mc = new myClass;

-Mike
Jul 22 '05 #2
Sumit Nagpal wrote:
My application reads a 'Class' name (as a string) from a file at Run time.
Can i create an instance this Class ?


Look up Factory Pattern, and Prototype Pattern with Google.com

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 22 '05 #3

"Sumit Nagpal" wrote:
My application reads a 'Class' name (as a string) from a file at Run time.
Can i create an instance this Class ?

You must add infrastructure: create object factory which
takes string and outputs heap allocated class.

/Pavel
Jul 22 '05 #4

"Sumit Nagpal" <su***@noida.at renta.com> schrieb im Newsbeitrag
news:2t******** *****@uni-berlin.de...
Hi All,

My application reads a 'Class' name (as a string) from a file at Run time.
Can i create an instance this Class ?

No.

Typically you would create a factory or at least a factory method,
which creates an object based on the class name.

Regards
Michael
Jul 22 '05 #5
Perhaps I didnt ask my question in properly.

Say, I write some code in core.so and some other person writes plugin.so
& plugin.txt
plugin.txt has a string "MyClass"
plugin.so has the definition of MyClass

While writing core.so I dont know anything about MyClass.

so there is no question of comparing it with something.
please tell me if i am still unclear.

Thanks
Sumit

Michael Kurz wrote:
"Sumit Nagpal" <su***@noida.at renta.com> schrieb im Newsbeitrag
news:2t******** *****@uni-berlin.de...
Hi All,

My application reads a 'Class' name (as a string) from a file at Run time.
Can i create an instance this Class ?


No.

Typically you would create a factory or at least a factory method,
which creates an object based on the class name.

Regards
Michael

Jul 22 '05 #6
I certainly have to go for FACTORY method but in my case I need
something more...
I think 'dlsym' should work for me !

Sumit Nagpal wrote:
Perhaps I didnt ask my question in properly.

Say, I write some code in core.so and some other person writes plugin.so
& plugin.txt
plugin.txt has a string "MyClass"
plugin.so has the definition of MyClass

While writing core.so I dont know anything about MyClass.

so there is no question of comparing it with something.
please tell me if i am still unclear.

Thanks
Sumit

Michael Kurz wrote:
"Sumit Nagpal" <su***@noida.at renta.com> schrieb im Newsbeitrag
news:2t******** *****@uni-berlin.de...
Hi All,

My application reads a 'Class' name (as a string) from a file at Run
time.
Can i create an instance this Class ?


No.

Typically you would create a factory or at least a factory method,
which creates an object based on the class name.

Regards
Michael

Jul 22 '05 #7
Sumit Nagpal wrote:
I certainly have to go for FACTORY method but in my case I need
something more...
I think 'dlsym' should work for me !


Warning ... try to steer away from dlsym. This reqyures you to know
what the mangling convention is - this is not portable.

Austria C++ (Shameless plug) has a solution for you and it works with
DLL's or DSO's.

Below is an example.
-------------- test code ------------------

#include "interface. h"

#include "at_factory .h"

using namespace at;
#include <iostream>
#include <dlfcn.h>
void Test( Interface * ptr )
{
if ( ! ptr )
{
std::cout << "There is no ptr\n";
return;
}

std::cout << "Thingy() = " << ptr->Thingy() << "\n";
std::cout << "Thingy1() = " << ptr->Thingy1() << "\n";
std::cout << "Thingy2() = " << ptr->Thingy2() << "\n";

bool is_del = false;

ptr->MarkPtr( & is_del );

delete ptr;

std::cout << ( is_del ? "Deleted" : "Not Deleted" ) << "\n";

}
void testfactory()
{
Interface * ptr =
FactoryRegister < Interface, DKy, Creator1P< Interface, DKy,
const char * > >
::Get().Create( "ImplementorKEY " )( "contructor param" );

Test( ptr );

ptr =
FactoryRegister < Interface, DKy, Creator2P< Interface, DKy,
const char *, const char * > >
::Get().Create( "ImplementorKEY " )( "contructor param1",
"contructor param2" );

Test( ptr );
}

void loaddso()
{
if ( ! dlopen( "xxx_dso.so ", RTLD_LAZY ) )
{
std::cerr << "dlopen error is: " << dlerror();
}
}

int main()
{

/* output should be :
There is no ptr
There is no ptr
*/

testfactory();

// load the objects ...
loaddso();

/*output should now be :
Thingy() = contructor param
Thingy1() =
Thingy2() =
Deleted
Thingy() = contructor param1
Thingy1() = contructor param2
Thingy2() =
Deleted
*/

testfactory();

}

------------------- interface.h -------------------------

class Interface
{

public:

virtual const char * Thingy() = 0;
virtual const char * Thingy1() = 0;
virtual const char * Thingy2() = 0;

bool * mark_del;

Interface()
: mark_del( 0 )
{
}

virtual ~Interface()
{
if ( mark_del )
{
* mark_del = true;
}
}

void MarkPtr( bool * i_mark_del )
{
mark_del = i_mark_del;
}

virtual int ContructParamCo unt() = 0;

};
--------------- implementation code ---- xxx_dso.cpp ----------

#include "interface. h"

#include "at_factory .h"

using namespace at;
class Implementor
: public Interface
{

public:

virtual const char * Thingy()
{
return m_str;
}

virtual const char * Thingy1()
{
return m_str2;
}

virtual const char * Thingy2()
{
return m_str3;
}

Implementor( const char * str, const char * str2, const char *
str3 )
: m_str( str ),
m_str2( str2 ),
m_str3( str3 ),
contruction_par ameter_count( 3 )
{
}

Implementor( const char * str, const char * str2 )
: m_str( str ),
m_str2( str2 ),
m_str3( "" ),
contruction_par ameter_count( 2 )
{
}

Implementor( const char * str )
: m_str( str ),
m_str2( "" ),
m_str3( "" ),
contruction_par ameter_count( 1 )
{
}

Implementor()
: m_str( "" ),
m_str2( "" ),
m_str3( "" ),
contruction_par ameter_count( 0 )
{
}

virtual int ContructParamCo unt()
{
return contruction_par ameter_count;
}

int contruction_par ameter_count;

const char * m_str;
const char * m_str2;
const char * m_str3;
};
AT_MakeFactory0 P( "ImplementorKEY ", Implementor, Interface, DKy );
AT_MakeFactory1 P( "ImplementorKEY ", Implementor, Interface, DKy, const
char * );
AT_MakeFactory2 P( "ImplementorKEY ", Implementor, Interface, DKy, const
char *, const char * );
AT_MakeFactory3 P( "ImplementorKEY ", Implementor, Interface, DKy, const
char *, const char *, const char * );

Jul 22 '05 #8

"Sumit Nagpal" <su***@noida.at renta.com> schrieb im Newsbeitrag
news:2t******** *****@uni-berlin.de...
Perhaps I didnt ask my question in properly.

Say, I write some code in core.so and some other person writes plugin.so
& plugin.txt
plugin.txt has a string "MyClass"
plugin.so has the definition of MyClass

While writing core.so I dont know anything about MyClass.

so there is no question of comparing it with something.


So If Iam right that *.so is a dynamic link library on linux (Iam more
familar with the windows stuff: DLL)
You need to export symbols, which can be used:

Thats how COM does it (roughly, adapted to your question):
- Define a Factory Interface (abtract base class), which is able to create
objects by a given class name and returns a pointer to the created object,
as you probably want to create different kinds of objects, of course all
objects created with one factory (factory interface) should share the
(abstract) BaseClass.

-Define an exported function within your *.so / *.dll file, which returns a
pointer to the factory.
(COM: CoGetClassObjec t), to make this compiler independent you could make
this function with C Linkage (extern "C")

If you want something like:
*.so contains a class, you only know the name nothing else about the class
and you want to create an instance without providing an Interface, well this
will not work with C++.

Regards
Michael
Jul 22 '05 #9
Sumit Nagpal wrote:

Perhaps I didnt ask my question in properly.

Say, I write some code in core.so and some other person writes plugin.so
& plugin.txt
plugin.txt has a string "MyClass"
plugin.so has the definition of MyClass

While writing core.so I dont know anything about MyClass.


Right.

I would do it this way:
All your plugins contain one class, which represents the plugin.
All those classes are derived from a common base class. All the
core knows about is a collection of pointers to those in order
to route commands to them.
So how then is the real plugin object created?
Simple: Each plugin.so has a function 'Create' which creates
the real plugin object and returns a pointer to it. And the
plugin.so knows about its real class.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #10

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

Similar topics

3
10807
by: Kiyomi | last post by:
Hello, I create a Table1 dynamically at run time, and at the same time, I would like to create LinkButton controls, also dynamically, and insert them into each line in my Table1. I would then like that, when clicking the LinkButton, the user can be navigated to another page, carrying a variable. I would like to use server.transfer method instead of QueryString as I don't want the carried variable to be visible for the user.
4
20303
by: DotNetJunkies User | last post by:
Hi, Does anyone know how/if you can instantiate a C# reference type object dynamically? More specifically, my project has a number of classes that I've created and in some cases it would be very handy to be able to instantiate them based on a string variable representing their class name. Here's an example of what I'd be looking to do. public object DynamicInstantiation(string className) { return new ; }
1
1748
by: Me, Myself, and I | last post by:
First off, i apologize if my terminology is off... I am currently in a project that is basically a front-end to a database. In coding this, I am taking into account that it has the *potential* to be front-ended on multiple databases as well as rendered in multiple browser types. That being said, is there a pre-constructed class out there that I can call from within my code to systematically "build" my SQL statement and have it take...
4
17028
by: Ray | last post by:
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 {
4
1491
by: Andrew Backer | last post by:
Hello, I am having a problem creating a class dynamically. The class I have is a base class of another, and the parent class has the constructor (which takes one argument). The base class (Class1, below) does not have any constructors. I am using code like this to create it, and it's blowing up : Dim res As Object = Activator.CreateInstance( _ GetType( MyNameSpace.Class1 ), _
4
3663
by: Tomas | last post by:
A newbie question: How can I instantiate objects dynamically in VB.NET. E.g. I have the object 'Player' and I would like to instantiate it with the several instances (James, Gunner, etc.), without in advance knowing how many objects (employee1, employee2, etc) Dim player1 As New Persons.Players Dim player2 As New Persons.Players Dim player3 As New Persons.Players ....
2
3120
by: Smithers | last post by:
Using 3.5, I am stuck in attempting to: 1. Dynamically load an assembly 2. Instantiate a class from that assembly (the client code is in a different namespace than the namespace of the dynamically loaded assembly) so far so good (per my code below)... but here is where I'm getting hung up: 3. Call methods of that type (see comments in my code) If the types in the dynamically loaded assembly were in the same namespace
8
3863
by: =?Utf-8?B?U2hhd24=?= | last post by:
Hi; i just started research reflection and i'm wondering if i have an empty class file can i use reflection to add member variables and attributes dynamically and then instantiate the class? What i would like to be able to do is start with and empty class, then depending on the data provided to me by a config file, add the member variables and attributes to the class temporarily. when the app is shutdown all changes would be gone. can...
7
3241
by: Joe Strout | last post by:
I have a function that takes a reference to a class, and then instantiates that class (and then does several other things with the new instance). This is easy enough: item = cls(self, **itemArgs) where "cls" is the class reference, and itemArgs is obviously a set of keyword arguments for its __init__ method. But now I want to generalize this to handle a set of mix-in classes.
0
9619
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10103
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9911
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.