473,324 Members | 2,179 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,324 software developers and data experts.

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 2452

"Sumit Nagpal" <su***@noida.atrenta.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("myfile");
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.atrenta.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.atrenta.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.atrenta.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 ContructParamCount() = 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_parameter_count( 3 )
{
}

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

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

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

virtual int ContructParamCount()
{
return contruction_parameter_count;
}

int contruction_parameter_count;

const char * m_str;
const char * m_str2;
const char * m_str3;
};
AT_MakeFactory0P( "ImplementorKEY", Implementor, Interface, DKy );
AT_MakeFactory1P( "ImplementorKEY", Implementor, Interface, DKy, const
char * );
AT_MakeFactory2P( "ImplementorKEY", Implementor, Interface, DKy, const
char *, const char * );
AT_MakeFactory3P( "ImplementorKEY", Implementor, Interface, DKy, const
char *, const char *, const char * );

Jul 22 '05 #8

"Sumit Nagpal" <su***@noida.atrenta.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: CoGetClassObject), 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
Yeah but if I do extern 'C' for that particular symbol, there wont be
any name mangling problem.

Thanks
Sumit Nagpal
Gianni Mariani wrote:
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 ContructParamCount() = 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_parameter_count( 3 )
{
}

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

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

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

virtual int ContructParamCount()
{
return contruction_parameter_count;
}

int contruction_parameter_count;

const char * m_str;
const char * m_str2;
const char * m_str3;
};
AT_MakeFactory0P( "ImplementorKEY", Implementor, Interface, DKy );
AT_MakeFactory1P( "ImplementorKEY", Implementor, Interface, DKy, const
char * );
AT_MakeFactory2P( "ImplementorKEY", Implementor, Interface, DKy, const
char *, const char * );
AT_MakeFactory3P( "ImplementorKEY", Implementor, Interface, DKy, const
char *, const char *, const char * );

Jul 22 '05 #11
You are right but I was talking about the situations where I'll have
multiple unkown plugins.
Now I have the solution for it 'dlsym' which will allow me to
instantiate all plugin classes with all plugin.so having 'Create' functions.

Thanks
Sumit
Karl Heinz Buchegger wrote:
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.

Jul 22 '05 #12

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

Similar topics

3
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...
4
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...
1
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*...
4
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...
4
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...
4
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...
2
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...
8
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...
7
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,...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.