473,796 Members | 2,751 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Typecasting portability in C

What I am trying to do is implement polymorphism in C. Why? This is to
build a library which will be a C library and callable from C.
However, I want to have polymorphic functions which are callable from
outside the library. Specifically I want to have functions like Show()
which will take a pointer to an object and do something different
based on the type object passed to it. Of course this would be trival
in C++ but I'm restricted to use C.

OK so my current idea for something like the polymophic Show()
routine: Since all the objects are created inside the library I can
attach to each object a signature. The Show() routine would accept a
void* but then typecast it and get the signature out of the object.
Since each object is a structure (and created and defined inside the
library) I would append this signature to the front of each and every
struct. The signature would likely be something like an integer. So
each and every object would look like:

struct SomeObjectType {
int signature;
.....//bunch other other stuff
};

The Show() routine would typecast the void* to the following
structure:

struct {
int signature;
}

So my Show() and similar polymorphic routines would get the object and
ultimatly open it and look at the first field which would always be
the signature object. Based on what it found there (the value of
signature) it would do something different. Makes sense? I hope so.

So I have implemented some prototype code on this and it does work but
what I was wondering is how portable is this? The structure's first
item (the signature) will always be the same this I can guarantee but
again what about portability. Really I'm converting from a pointer to
one type, to a void*, then to a pointer to another type (for signature
extraction). Certainly the first object in the final structure will be
the same as the first object in the original structure and the same
size as well. But does that make it portable?

Is this legal C as defined by the standard? Is this going to work
across platforms? I hope you see my dilemma the code appears to work
on my system. The code below happily prints the expected output of
112. but I don't know if it's guaranteed to work everywhere and how
portable the library functions will be because of it?

Is this defined in any C standard anywhere what will happen and what
about general portability concerns?

In the example below I defined a structure CouldBeAnything and filled
it with a long and a char but really not only that structure but
anything after that initial signature integer will be different from
object to object. The only thing I can guarantee is that the first
item will be that signature integer on each object. Will this
conversion work? Is it portable? It works on my machine but does that
mean it will work in general? Thank you. :)

---
//On the code below when run on my machine it happily prints out 112
//No warnings are given by the gcc complier with warning flag -Wall

#include <stdio.h>

//This structure could contain anything
struct CouldBeAnything
{
long ThisTimeItsALon g;
char AndAChar;
};

struct MinimalStructur e
{
int Signature;
};
struct LargerStructure
{
int Signature;
struct CouldBeAnything SomeStructure;
};

int main ()
{
struct LargerStructure SomeLargeStruct ure;

SomeLargeStruct ure.Signature = 112;
SomeLargeStruct ure.SomeStructu re.ThisTimeItsA Long = 1;
SomeLargeStruct ure.SomeStructu re.AndAChar = 'a';

struct MinimalStructur e* Minimal = ( struct MinimalStructur e* )
&SomeLargeStruc ture;

printf( "Signature = %d\n", Minimal->Signature );
return 0;
}

Jan 28 '07
12 1732
ch************* ****@yahoo.com wrote:
What I am trying to do is implement polymorphism in C. Why? This is to
build a library which will be a C library and callable from C.
However, I want to have polymorphic functions which are callable from
outside the library. Specifically I want to have functions like Show()
which will take a pointer to an object and do something different
based on the type object passed to it. Of course this would be trival
in C++ but I'm restricted to use C.

OK so my current idea for something like the polymophic Show()
routine: Since all the objects are created inside the library I can
attach to each object a signature. The Show() routine would accept a
void* but then typecast it and get the signature out of the object.
Since each object is a structure (and created and defined inside the
library) I would append this signature to the front of each and every
struct. The signature would likely be something like an integer. So
each and every object would look like:

struct SomeObjectType {
int signature;
....//bunch other other stuff
};

The Show() routine would typecast the void* to the following
structure:

struct {
int signature;
}

So my Show() and similar polymorphic routines would get the object and
ultimatly open it and look at the first field which would always be
the signature object. Based on what it found there (the value of
signature) it would do something different. Makes sense? I hope so.
As you were told elsewhere, it won't work. But you can do same
thing with

struct Base {
int signature;
};

struct Child {
struct Base base;
long something;
};

It will require a cast if you got Child* and want Base members, but
it's not really high price.

Yevgen
Jan 30 '07 #11
Thad Smith wrote:
Eric Sosman wrote:
>Thad Smith wrote:
>>ch************* ****@yahoo.com wrote:

What I am trying to do is implement polymorphism in C.

...

I would append this signature to the front of each and every struct.
The signature would likely be something like an integer. So each and
every object would look like:

struct SomeObjectType {
int signature;
....//bunch other other stuff
};

The Show() routine would typecast the void* to the following structure:

struct {
int signature;
}

...

Is this legal C as defined by the standard?
Yes. If the initial sequence of two structures match, the members in
the initial sequence can be accessed through either structure type.


... provided the two structs are members of the same union.
A compiler would need to be awfully smart and awfully perverse
to arrange things so the presence of the union made any difference,
but the formal guarantee has union membership ("Look for ... the
union label") as a precondition.

Thanks, Eric for that important correction.

As far as perverse goes, here's a possibility:

An implementation has an alignment requirement that an int be on an
4-byte boundary and single byte objects are accessed faster on even
addresses than odd addresses.

Given
struct S1 {
char a,b;
} s1;

struct S2 {
char a,b;
int c;
} s2;

The implementation may choose to implement S1 with no padding bytes, and
S2 with a single padding byte between a and b, and another between b and
c. That arrangement gives faster accesss to s2.b, while keeping the
size of struct S1 to a minimum.
This is the same point as my answer to Harald van Dijk. So the trick is
to put an anonymous 0 length bit field after the matching part:

struct S1 {
char a,b;
};

struct S2 {
char a,b;
int :0;
int c;
};

struct S3 {
struct S1 s;
int c;
};

Then S1, S2 and S3 should have compatible layout on the common part
whatever the field are in this part. This is what OOC-2.0 does and I
haven't seen problem with that. I don't know if anonymous 0 length bit
field was created for this purpose, but it works fine.

a+, ld.
Jan 30 '07 #12
OK so my current idea for something like the polymophic Show()
routine: Since all the objects are created inside the library I can
attach to each object a signature. The Show() routine would accept a
void* but then typecast it and get the signature out of the object.
Since each object is a structure (and created and defined inside the
library) I would append this signature to the front of each and every
struct. The signature would likely be something like an integer. So
each and every object would look like:

struct SomeObjectType {
int signature;
....//bunch other other stuff
};

V-Table is what you want. Something like:

typedef struct VTableForVehicl e {
void (*StartEngine)( void);
void (*Accelerate)(u nsigned);
void (*Brake)(unsign ed);
} VTableForVehicl e;

Provide definitions for each of the functions for each kind of vehicle:

void Car_StartEngine (void) { /* Code */ }
void Car_Accelerate( unsigned) { /* Code */ }
void Car_Brake(unsig ned) { /* Code */ }
void Bike_StartEngin e(void) { /* Code */ }
void Bike_Accelerate (unsigned) { /* Code */ }
void Bike_Brake(unsi gned) { /* Code */ }

Then populate global const v-table objects for each kind of vehicle:

VTableForVehicl e const
vtab_car = {Car_StartEngin e,Car_Accelerat e,Car_Brake},
vtab_bike = {Bike_StartEngi ne,Bike_Acceler ate,Bike_Brake} ;

Now put a V-Table pointer at the beginning of each vehicle object, then put
a vehicle object inside every car, every bike:

typedef struct Vehicle { VTableForVehicl e const *pvtab; } Vehicle;

typedef struct Car { Vehicle vehicle; } Car;
typedef struct Bike { Vehicle vehicle; } Bike;

And "initialise " it as follows:

Car obj = { {vtab_car} };

Then polymorphism can be exploited as follows:

void FuncWhichTakesA Vehicle(Vehicle *const p)
{
p->Accelerate() ;
}

Bit of a snappy explanation but you get the idea.

--
~/JB\~
Feb 7 '07 #13

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

Similar topics

3
8187
by: Kapil Khosla | last post by:
Hi, I have been trying to understand this concept for quite sometime now somehow I am missing some vital point. I am new to Object Oriented Programming so maybe thats the reason. I want to understand what is typecasting in C++. Say I have a Base class and a Derived class, I have a pointer to an object to each. Base *ba = new Base; Derived *de = new Derived;
7
4546
by: Nicolay Korslund | last post by:
Hi! I'm having a little trouble with the typecast operator, can anybody help me with the rules for when the this operator is invoked? In the class 'Test' in the code below, the typecast operator returns a 'mytype'. In main() I use the operator on 'Test'-class objects. If 'mytype' is a pointer the operator works fine. But if I instead try to call an overloaded operator, the typecast operator is not invoked, and I get a compiler error...
2
4180
by: Arun Prasath | last post by:
Hi all, I have the following question regd pointer typecasting. Is the following type of pointer typecasting valid? #define ALLOC(type,num) ((type *)malloc(sizeof(type)*num)) /*begin code*/
63
3424
by: andynaik | last post by:
Hi, Whenever we type in this code int main() { printf("%f",10); } we get an error. We can remove that by using #pragma directive t direct that to the 8087. Even after that the output is 0.00000 and no 10.0000. Can anybody tell me why it is like that and why typecasting i not done in this case?
11
4426
by: Vinod Patel | last post by:
I have a piece of code : - void *data; ...... /* data initialized */ ...... struct known_struct *var = (struct known_struct*) data; /*typecasting*/ How is this different from simple assignment. int b = some_value;
93
3687
by: roman ziak | last post by:
I just read couple articles on this group and it keeps amazing me how the portability is used as strong argument for language cleanliness. In my opinion, porting the program (so you just take the source code and recompile) is a myth started 20-30 years ago when world consisted of UNIX systems. Well, world does not consist of UNIX systems anymore, but there are 100s of different systems running in cell-phones, DVD players, game consoles...
3
1647
by: jdm | last post by:
In the sample code for the SortedList class, I see the use of a string typecasting macro consisting of a single letter "S". i.e.: Sortedlist->Add(S"Keyval one", S"Item one"); Now I have deduced that the "S" can be replaced with (String __gc *) and the code will compile and run just fine. But what I can't find is what exactly Microsoft calls these macros (I have also seen "L" used the same way) and where they are all documented. I...
12
4481
by: bwaichu | last post by:
What is the best way to handle this warning: warning: cast from pointer to integer of different size I am casting in and out of a function that requires a pointer type. I am casting an integer as a pointer, but the pointer is 8 bytes while the integer is only 4 bytes. Here's an example function:
0
1151
by: ctj951 | last post by:
What I am trying to do is implement polymorphism in C. Why? This is to build a library which will be a C library and callable from C. However, I want to have polymorphic functions which are callable from outside the library. Specifically I want to have functions like Show() which will take a pointer to an object and do something different based on the type object passed to it. Of course this would be trival in C++ but I'm restricted to use...
26
12569
by: Nishu | last post by:
Hi All, Is it valid in C to typecast a pointer? eg. code snippet... considering int as 16 bit and long as 32 bit. int *variable, value; *((long*)variable)++ = value; *((long*)variable)++ = value;
0
9685
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
9535
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
10467
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
10244
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...
0
9061
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...
0
6802
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
5454
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...
2
3744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2931
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.