473,786 Members | 2,849 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
11 2496
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 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 #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
10808
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
1749
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
3865
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
3242
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
9647
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
10363
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9961
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...
1
7512
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6745
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5397
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4066
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
3669
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.