473,779 Members | 1,873 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Wrapper around C lib, problem with c_str and const

Hi

I'm writing a class to act as a wrapper around a C library.

This C library exposes functions like:

SetSomeInfo( char *pTheInfo );

In my wrapper class, the info in question is in a STL string.

std::string m_TheInfo;

So inside the wrapper class I would like to call:

SetSomeInfo( m_TheInfo.c_str () );

But, problem:

c_str returns a const char *, and SetSomeInfo accepts a char * (not
const), so it doesn't compile. Maybe SetSomeInfo is poorly written,
because it should have const in its signature, but it's not mine and
I have no control over it.

So my (rather ugly) workaround right now is:

char *p = (char *)(DWORD) m_TheInfo.c_str () ; //get rid of const

but surely there has to be a more standard way ?

Thanks

Sep 10 '05 #1
5 1932
Fred Paris wrote:
[snip]

char *p = (char *)(DWORD) m_TheInfo.c_str () ; //get rid of const

but surely there has to be a more standard way ?

Sure:

char *p = const_cast<char *>(m_TheInfo.c_ str());

But make sure that the function *really* doesn't modify 'p', otherwise
you might run into undefined behaviour.

If you want to be absolutely safe and more elegant (avoiding the
const_cast and possible undefined behaviour), you can do something
like:

enum { BUF_SIZE = 1024 };

char p[BUF_SIZE];
strncpy(p, m_TheInfo.c_str (), BUF_SIZE);
p[BUF_SIZE-1] = 0;

Hope this helps,
-shez-

Sep 10 '05 #2

"Fred Paris" <no**@nono.inva lid> wrote in message
news:pl******** *************** *********@4ax.c om...
Hi

I'm writing a class to act as a wrapper around a C library.

This C library exposes functions like:

SetSomeInfo( char *pTheInfo );

In my wrapper class, the info in question is in a STL string.

std::string m_TheInfo;

So inside the wrapper class I would like to call:

SetSomeInfo( m_TheInfo.c_str () );
The following should get you through compilation...b ut really ask yourself
if that is really what you want (notice the low level operations and
explicit exception handling which are rather ugly):

char* buff = new char[m_TheInfo.lengt h() + 1];
std::copy(buff, m_TheInfo.begin (), m_TheInfo.end() );
buff[m_TheInfo.lengt h()] = '\0';
try
{
SetSomeInfo(buf f);
}
catch (...)
{
delete[] buff;
throw;
}
delete[] buff;


But, problem:

c_str returns a const char *, and SetSomeInfo accepts a char * (not
const), so it doesn't compile. Maybe SetSomeInfo is poorly written,
because it should have const in its signature, but it's not mine and
I have no control over it.

So my (rather ugly) workaround right now is:

char *p = (char *)(DWORD) m_TheInfo.c_str () ; //get rid of const
Don't do this. You may corrupt the string object and your program may not
recover from such brutal operation. NOT COOL!! std::string::c_ str() returns
a const char* for a reason, most likely to set up protection against misuse.

but surely there has to be a more standard way ?

Thanks

Sep 10 '05 #3
"Fred Paris" <no**@nono.inva lid> wrote in message
news:pl******** *************** *********@4ax.c om
Hi

I'm writing a class to act as a wrapper around a C library.

This C library exposes functions like:

SetSomeInfo( char *pTheInfo );

In my wrapper class, the info in question is in a STL string.

std::string m_TheInfo;

So inside the wrapper class I would like to call:

SetSomeInfo( m_TheInfo.c_str () );

But, problem:

c_str returns a const char *, and SetSomeInfo accepts a char * (not
const), so it doesn't compile. Maybe SetSomeInfo is poorly written,
because it should have const in its signature, but it's not mine and
I have no control over it.

So my (rather ugly) workaround right now is:

char *p = (char *)(DWORD) m_TheInfo.c_str () ; //get rid of const

but surely there has to be a more standard way ?

Thanks

SetSomeInfo(con st_cast<char*>( m_TheInfo.c_str () ));
--
John Carson
Sep 10 '05 #4
benben wrote:

The following should get you through compilation...b ut really ask yourself
if that is really what you want (notice the low level operations and
explicit exception handling which are rather ugly):

Or, you could just use a vector<char>:

vector<char> buff(m_TheInfo. length() + 1);
....

This gets rid of all the exception handling ugliness. Note however
that vector<char> will likely allocate, and if you know that the string
is never going to be more than a certain length, its probably better if
you just use a local buffer. You might want to throw an exception if
it exceeds this "maximum" length.

Many people often underestimate the cost of allocation/deallocation,
especially in multi-threaded environments where memory contention
becomes a much bigger issue than in single-threaded environments.

Hope this helps,
-shez-

Sep 10 '05 #5

"Shezan Baig" <sh************ @gmail.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
benben wrote:

The following should get you through compilation...b ut really ask
yourself
if that is really what you want (notice the low level operations and
explicit exception handling which are rather ugly):
Or, you could just use a vector<char>:

vector<char> buff(m_TheInfo. length() + 1);


Eureka! Sure, I just forgot that a vector guarantees continuous memory block
haha.
...

This gets rid of all the exception handling ugliness. Note however
that vector<char> will likely allocate, and if you know that the string
is never going to be more than a certain length, its probably better if
you just use a local buffer. You might want to throw an exception if
it exceeds this "maximum" length.
That is to say we need a better allocator.

Many people often underestimate the cost of allocation/deallocation,
especially in multi-threaded environments where memory contention
becomes a much bigger issue than in single-threaded environments.

Hope this helps,
-shez-

Sep 10 '05 #6

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

Similar topics

4
2761
by: kazack | last post by:
I posted a similiar question in this newsgroup already and got an answer which I already knew but didn't get the answer I was looking for so I am reposting the code and question differently in the hope that someone could help me out. As said in an earlier post I am new to c++, this is alot harder to do than VB. I am for the most part self taught with what I already know and looking to learn more. The book I am using to teach myself from...
4
2212
by: Anton Pervukhin | last post by:
Hi everybody! I have a small problem regarding the initialization of pointer to the file stream under some conditions. Imagine a class which has a pointer to output file stream and some additinional methods to deal with it, i.e. open/close/write: classA { private: const std::auto_ptr<std::ofstream> filePtr;
3
4046
by: railrulez | last post by:
Hi, Attached is a program which uses a hash_set, but I cant seem to get find() or iterators working on it. I'm not sure whether hash_set is std C++, but I dont know where else to ask. ----------------------------- #include <iostream> #include <fstream>
7
2370
by: matish | last post by:
Hi, in: string s("Hi"); const char* c = s.c_str(); how long will the pointed cstring live? I see that calling delete c or delete c fail, that the cstring survives the end of the scope in witch it is decleard and even delete s does not
9
2340
by: ma740988 | last post by:
Assume I have a vendor file called ' vendor.h'. Within the file there's two methods memalign and cforward. It is my understanding that the memalign function is a wrapper around malloc. cforward is just a vendor function for doing forward FFT's. At issue CSL_COMPLEX is 'cumbersome' to work with. As a result I created a wrapper. So now - given the pseudo code. #include <iostream> #include <complex> #include <vector>
15
3658
by: Gan Quan | last post by:
I'm writing a c++ program that has many (100+) threads read/write files simultaneously. It works well if not considering the efficiency. The file i/o seems to be the bottleneck. This is my code to read from and write to files: #include <fstream> #include <sstream> #include <string>
5
1923
by: B. Williams | last post by:
I need some assistance with random access file processing. I have a function that I would like to change from sequential file processing to random access. Thanks in advance. void updatePower(string filename) { ifstream in(filename.c_str(), ios::in); int cnt = 0; // read all records into database until we reach the end of the file
0
334
by: Sandy | last post by:
HI All, I have created a MFC exe using VC++ .NET 2003 on Windows XP Prof service pack 2 and it works properly on my machine, but when I run the same exe on a different machine (Windows XP Prof SP-2), The application is bought up and after some time its throwing a windows xp error dialog
17
5819
by: Chris M. Thomasson | last post by:
I use the following technique in all of my C++ projects; here is the example code with error checking omitted for brevity: _________________________________________________________________ /* Simple Thread Object ______________________________________________________________*/ #include <pthread.h> extern "C" void* thread_entry(void*);
0
9632
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
10136
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
10071
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
8958
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
7478
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
6723
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
5372
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
5501
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4036
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

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.