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

Mixing C and C++

I have an existing ANSI C library which makes extensive use of structs.
I use these structs in my C++ code, but would like to benefit from C++
features such as ctors/dtors etc. I have modified the C header, as shown
below, with inline functions, so that I can benefit from C++ features,
whilst keeping the rest of the C library intact.

One thing I had to be particularly careful of is the fact that in a lot
of the C API functions, struct assignments were made (i.e. shallow
copies). I have therefore implemented the (overloaded) assignment
operator to create 'shallow' copy by default (so this is consistent with
the C API so that a pointer to the struct could be passed to a C API
function with no adverse effect). The facility still exists for an
(explicit) deepcopy. This is is what I have come up with so far. The CPP
snippet at the end of the post shows how I intend to use it.
//Header File

#ifdef __cplusplus
extern "C"
{
#endif

struct MyStruct
{
public:
MyStruct(const size_t size)
:m_shallow_copied(false)
{
if (!fooAlloc(this, size))
throw new std::bad_alloc ;
}

MyStruct(const MyStruct& ms)
:m_shallow_copied(false)
{
//deep copy because only C++ API calls this ctor
copy(ms, true);
}

MyStruct& operator= (const MyStruct& rhs)
{
//Default shallow copy on assignments
if (this != &rhs)
copy(rhs);
return *this ;
}

//explicit deepcopy
void deepcopy(const struct MyStruct* rhs)
{
copy(rhs,true);
}

~MyStruct::MyStruct
{
if (!m_shallow_copied && m_ptr)
fooFree(this);
}

//Needs to be public - for C API (too many funcs to all be friends)
void * m_ptr ;
size_t m_size ;

private:
void copy(const MyStruct& rhs, const bool deepcopy=false)
{
if (deepcopy)
{
//do we own ptr? (if so, free first)
if (m_ptr && !m_shallow_copied)
fooFree(this);

if (fooAlloc(this, rhs.size ))
throw new std::bad_alloc ;

fooCopy(this, &rhs) ;
m_shallow_copied = false ;
}
else
{
//default
m_ptr = rhs.m_ptr ;
m_size = rhs.m_size ;
m_shallow_copied = true ;
}
}

bool m_shallow_copied ;
};
/* Pure C API */
long fooAlloc(struct MyStruct* ms, const unsigned int size);
void fooFree(struct MyStruct* ms);
void fooCopy(struct MyStruct* dest, const struct MyStruct* src);
long fooJustDoIt(const struct MyStruct* ms);

#ifdef __cplusplus
};
#endif

//Sample cpp file using MyStruct (should probably use auto_ptr instead
of raw pointers ...)

#include "MyStruct.h"

class MyClass
{
public:
MyClass(const size_t s)
{ ms = new MyStruct(s); }

MyClass(const MyClass&);

~MyClass()
{delete ms ;}

long DoSomething() const
{
//pass ptr to MyStruct to C function
return fooJustDoIt(ms);
}

private:
MyStruct * ms ;
};
I would appreciate some feedback as to whether there are any subtle (or
not so subtle) caveats/gotchas I must be aware of with this approach ...
Jul 1 '07 #1
8 2028

"Grey Alien" <gr**@andromeda.comwrote in message
news:ts******************************@bt.com...
>I have an existing ANSI C library which makes extensive use of structs. I
use these structs in my C++ code, but would like to benefit from C++
features such as ctors/dtors etc. I have modified the C header, as shown
below, with inline functions, so that I can benefit from C++ features,
whilst keeping the rest of the C library intact.

One thing I had to be particularly careful of is the fact that in a lot of
the C API functions, struct assignments were made (i.e. shallow copies). I
have therefore implemented the (overloaded) assignment operator to create
'shallow' copy by default (so this is consistent with the C API so that a
pointer to the struct could be passed to a C API function with no adverse
effect). The facility still exists for an (explicit) deepcopy. This is is
what I have come up with so far. The CPP snippet at the end of the post
shows how I intend to use it.
//Header File

#ifdef __cplusplus
extern "C"
{
#endif

struct MyStruct
{
public:
MyStruct(const size_t size)
:m_shallow_copied(false)
{
if (!fooAlloc(this, size))
throw new std::bad_alloc ;
}

MyStruct(const MyStruct& ms)
:m_shallow_copied(false)
{
//deep copy because only C++ API calls this ctor
copy(ms, true);
}

MyStruct& operator= (const MyStruct& rhs)
{
//Default shallow copy on assignments
if (this != &rhs)
copy(rhs);
return *this ;
}

//explicit deepcopy
void deepcopy(const struct MyStruct* rhs)
{
copy(rhs,true);
}

~MyStruct::MyStruct
{
if (!m_shallow_copied && m_ptr)
fooFree(this);
}

//Needs to be public - for C API (too many funcs to all be friends)
void * m_ptr ;
size_t m_size ;

private:
void copy(const MyStruct& rhs, const bool deepcopy=false)
{
if (deepcopy)
{
//do we own ptr? (if so, free first)
if (m_ptr && !m_shallow_copied)
fooFree(this);

if (fooAlloc(this, rhs.size ))
throw new std::bad_alloc ;

fooCopy(this, &rhs) ;
m_shallow_copied = false ;
}
else
{
//default
m_ptr = rhs.m_ptr ;
m_size = rhs.m_size ;
m_shallow_copied = true ;
}
}

bool m_shallow_copied ;
};
/* Pure C API */
long fooAlloc(struct MyStruct* ms, const unsigned int size);
void fooFree(struct MyStruct* ms);
void fooCopy(struct MyStruct* dest, const struct MyStruct* src);
long fooJustDoIt(const struct MyStruct* ms);

#ifdef __cplusplus
};
#endif

//Sample cpp file using MyStruct (should probably use auto_ptr instead of
raw pointers ...)

#include "MyStruct.h"

class MyClass
{
public:
MyClass(const size_t s)
{ ms = new MyStruct(s); }

MyClass(const MyClass&);

~MyClass()
{delete ms ;}

long DoSomething() const
{
//pass ptr to MyStruct to C function
return fooJustDoIt(ms);
}

private:
MyStruct * ms ;
};
I would appreciate some feedback as to whether there are any subtle (or
not so subtle) caveats/gotchas I must be aware of with this approach ...
How does it compile and link?
--
WW
Jul 1 '07 #2


Wade Ward wrote:
"Grey Alien" <gr**@andromeda.comwrote in message
news:ts******************************@bt.com...
<snip></snip>
>>
I would appreciate some feedback as to whether there are any subtle (or
not so subtle) caveats/gotchas I must be aware of with this approach ...

How does it compile and link?
--
WW

It compiles/links fine ... but I suspect that it is at run time that
I'll find signs that say "here be monsters" ... Since any problems are
likely to be caused by one (or more of the ff):

1). "dangling" pointers
2). Attempt to dealloc memory more than once
3). Attempt to free memory alloc'd with 'new' (or vice-versa)
4). memory leaks

I can't find that out yet for sure, because I'm still developing the
application.
Jul 1 '07 #3
Grey Alien wrote:
>
I have an existing ANSI C library which makes extensive use of
structs. I use these structs in my C++ code, but would like to
benefit from C++ features such as ctors/dtors etc. I have modified
the C header, as shown below, with inline functions, so that I can
benefit from C++ features, whilst keeping the rest of the C
library intact.

One thing I had to be particularly careful of is the fact that in
a lot of the C API functions, struct assignments were made (i.e.
shallow copies). I have therefore implemented the (overloaded)
assignment operator to create 'shallow' copy by default (so this
is consistent with the C API so that a pointer to the struct could
be passed to a C API function with no adverse effect). The
facility still exists for an (explicit) deepcopy. This is is what
I have come up with so far. The CPP snippet at the end of the post
shows how I intend to use it.

//Header File

#ifdef __cplusplus
extern "C"
{
#endif

struct MyStruct
{
public:
Here you are using C++ code, illegal in C. Thus off-topic here.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

Jul 1 '07 #4
Grey Alien wrote:
I have an existing ANSI C library which makes extensive use of
structs. I use these structs in my C++ code, but would like to
benefit from C++ features such as ctors/dtors etc.

That would make it a proper topic for comp.lang.c++.

Brian
Jul 1 '07 #5
In article <46***************@yahoo.com>,
CBFalconer <cb********@maineline.netwrote:
>#ifdef __cplusplus
extern "C"
....
>Here you are using C++ code, illegal in C. Thus off-topic here.
Since __cplusplus is not defined when using standard C, it's perfectly
legal C.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jul 1 '07 #6
Richard Tobin wrote:
In article <46***************@yahoo.com>,
CBFalconer <cb********@maineline.netwrote:
>>#ifdef __cplusplus
extern "C"
Restored sniped context
>>{
#endif

struct MyStruct
{
public:
>Here you are using C++ code, illegal in C. Thus off-topic here.

Since __cplusplus is not defined when using standard C, it's perfectly
legal C.
But the

struct MyStruct
{
public:

is illegal and not protected by an #ifdef.

Kevin.
Jul 1 '07 #7
In article <l3******************@newsfe7-gui.ntli.net>,
Kevin Bagust <ke**********@ntlworld.comwrote:
>But the

struct MyStruct
{
public:

is illegal and not protected by an #ifdef.
Yes, I didn't notice that.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jul 1 '07 #8
On Sun, 01 Jul 2007 00:56:34 +0100, Grey Alien <gr**@andromeda.comwrote:
I have an existing ANSI C library which makes extensive use of structs.
I use these structs in my C++ code, but would like to benefit from C++
features such as ctors/dtors etc. I have modified the C header, as shown
below, with inline functions, so that I can benefit from C++ features,
whilst keeping the rest of the C library intact.
I think it makes more sense to leave the C library alone (presumably
it works well as a C library) and create a separate C++ wrapper.
C++ is good at that kind of thing; it can be done with minimal
run-time performance penalty.

Mixing the two interfaces together just makes them harder to
understand, IMHO.

/Jorgen

--
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.dyndns.org R'lyeh wgah'nagl fhtagn!
Jul 3 '07 #9

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

Similar topics

3
by: bergel | last post by:
Hello, Does anyone already have some experience in mixing AWT and Swing? Is it conceptually doable? Does the design of Swing prevent interaction between an AWT and a Swing widget? Regards,...
6
by: Russell E. Owen | last post by:
At one time, mixing for x in file and readline was dangerous. For example: for line in file: # read some lines from a file, then break nextline = readline() # bad would not do what a naive...
0
by: Erik Max Francis | last post by:
Is there any prohibition against mixing different protocols within the same pickle? I don't see anything about this in the Python Library Reference and, after all, the pickle.dump function takes a...
4
by: Rudolf | last post by:
Is it possible to add a vb.net source code module to a c# project and if so how? Thanks Rudolf
1
by: Marc Cromme | last post by:
I would like to ask a question about (good ?) style and possibilities in mixing C FILE* and C++ file streams. The background is that I want to use the C libpng library from within C++, but I...
4
by: Cristian Tota | last post by:
Hi, I'd appreciate any thoughts on mixing C++ and C code. I have a project that uses a given C interface, the rest of the project can be either in C or C++. What would be the recomended design...
2
by: Dan | last post by:
Hi What are the dangers of mixing asp and asp.net? For the .net part of the site i will need to use the global.asax file but for the asp parts it will be using the other global. file, is there...
0
by: dhruba.bandopadhyay | last post by:
I know that it's possible to mix ASP & ASP.NET 1.1 in the same website/application so long as they are in separate frames (iframes). This also holds for mixing ASP & ASP.NET 2.0 pages. But what I...
28
by: ziman137 | last post by:
Hello all, I have a question and am seeking for some advice. I am currently working to implement an algorithmic library. Because the performance is the most important factor in later...
3
by: jason | last post by:
I've been working with C# for over a year now without touching vb.net code. I had a few light years of vb.net before that. No real vb6 or windows form experience. Suddenly, I have an assignment...
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: 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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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
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...
0
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,...
0
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...

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.