473,581 Members | 2,783 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using string where a char* required

I am working with a C API which often requires a char* or char buffer. If a
C function returns a char* I can't use string? Or can I? I realise I can
pass a char* using c_str() but what about receiving a char buffer into a
string?

Reason I ask is otherwise I have to guess at what size buffer to create?
And then copy buffer to a string. Doesn't seem ideal.

Jul 28 '07 #1
11 2689
"Angus" writes:
>I am working with a C API which often requires a char* or char buffer. If
a
C function returns a char* I can't use string? Or can I? I realise I can
pass a char* using c_str() but what about receiving a char buffer into a
string?

Reason I ask is otherwise I have to guess at what size buffer to create?
And then copy buffer to a string. Doesn't seem ideal.
One of the constructors for std::string will, in effect, accept a char* as
an parameter.

Thus:

char* foo { /*stuff*/ }

std::string s;
s= foo();

Or at least something similar to that.
Jul 28 '07 #2

"osmium" <r1********@com cast.netwrote in message
news:5h******** *****@mid.indiv idual.net...
"Angus" writes:
I am working with a C API which often requires a char* or char buffer.
If
a
C function returns a char* I can't use string? Or can I? I realise I
can
pass a char* using c_str() but what about receiving a char buffer into a
string?

Reason I ask is otherwise I have to guess at what size buffer to create?
And then copy buffer to a string. Doesn't seem ideal.

One of the constructors for std::string will, in effect, accept a char* as
an parameter.

Thus:

char* foo { /*stuff*/ }

std::string s;
s= foo();

Or at least something similar to that.
For example in Windows there is a GetUserName function like this:
BOOL WINAPI GetUserName ( LPWSTR lpBuffer, LPDWORD nSize )

if you do this:
std::string str;

DWORD bufsize = 256;

GetUserName(str , &bufsize);

you get compile error:

error C2664: 'GetUserNameA' : cannot convert parameter 1 from 'class
std::basic_stri ng<char,struct std::char_trait s<char>,class
std::allocator< char' to 'char *'
No user-defined-conversion operator available that can perform this
conversion, or the operator cannot be called
I suppose I could cast? But wondering what best way to tackle is.

Jul 28 '07 #3
Angus wrote:
"osmium" <r1********@com cast.netwrote in message
news:5h******** *****@mid.indiv idual.net...
>"Angus" writes:
>>I am working with a C API which often requires a char* or char
buffer. If a
C function returns a char* I can't use string? Or can I? I
realise I can pass a char* using c_str() but what about receiving a
char buffer into a string?

Reason I ask is otherwise I have to guess at what size buffer to
create? And then copy buffer to a string. Doesn't seem ideal.

One of the constructors for std::string will, in effect, accept a
char* as an parameter.

Thus:

char* foo { /*stuff*/ }

std::string s;
s= foo();

Or at least something similar to that.

For example in Windows there is a GetUserName function like this:
BOOL WINAPI GetUserName ( LPWSTR lpBuffer, LPDWORD nSize )

if you do this:
std::string str;

DWORD bufsize = 256;

GetUserName(str , &bufsize);

you get compile error:

error C2664: 'GetUserNameA' : cannot convert parameter 1 from 'class
std::basic_stri ng<char,struct std::char_trait s<char>,class
std::allocator< char' to 'char *'
No user-defined-conversion operator available that can perform
this conversion, or the operator cannot be called
I suppose I could cast? But wondering what best way to tackle is.
The best way is to allocate a temporary (local) array of TCHAR (or
whatever type is LPWSTR points to) and then _after_ you call the
function that would fill in that array, create a string from it.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 28 '07 #4
"Angus" writes:
"osmium" <r1********@com cast.netwrote in message
news:5h******** *****@mid.indiv idual.net...
>"Angus" writes:
>I am working with a C API which often requires a char* or char buffer.
If
>a
C function returns a char* I can't use string? Or can I? I realise I
can
pass a char* using c_str() but what about receiving a char buffer into
a
string?

Reason I ask is otherwise I have to guess at what size buffer to
create?
And then copy buffer to a string. Doesn't seem ideal.

One of the constructors for std::string will, in effect, accept a char*
as
an parameter.

Thus:

char* foo { /*stuff*/ }

std::string s;
s= foo();

Or at least something similar to that.

For example in Windows there is a GetUserName function like this:
BOOL WINAPI GetUserName ( LPWSTR lpBuffer, LPDWORD nSize )

if you do this:
std::string str;

DWORD bufsize = 256;

GetUserName(str , &bufsize);

you get compile error:

error C2664: 'GetUserNameA' : cannot convert parameter 1 from 'class
std::basic_stri ng<char,struct std::char_trait s<char>,class
std::allocator< char' to 'char *'
No user-defined-conversion operator available that can perform this
conversion, or the operator cannot be called
I suppose I could cast? But wondering what best way to tackle is.
I wonder if LPWSTR is, by chance, Microsoft gobbledygook for wide string?

Your question asked about a char* and char pointer points at a *byte*. So
all bets are off.

I get a headache just thinking about that crappy Microsoft stuff. If my
guess is right about the 'W', I guess the *right* way to proceed is to
fiddle with locales or facets or traits or some of that other high faultin'
stuff. But that's not the way I would proceed. I would find out what that
damn acronym represented in the real world and convert/cast/whatever to make
the thing work.
Jul 28 '07 #5

"osmium" <r1********@com cast.netwrote in message
news:5h******** *****@mid.indiv idual.net...
"Angus" writes:
"osmium" <r1********@com cast.netwrote in message
news:5h******** *****@mid.indiv idual.net...
"Angus" writes:

I am working with a C API which often requires a char* or char buffer.
If
a
C function returns a char* I can't use string? Or can I? I realise
I
can
pass a char* using c_str() but what about receiving a char buffer
into
a
string?

Reason I ask is otherwise I have to guess at what size buffer to
create?
And then copy buffer to a string. Doesn't seem ideal.

One of the constructors for std::string will, in effect, accept a char*
as
an parameter.

Thus:

char* foo { /*stuff*/ }

std::string s;
s= foo();

Or at least something similar to that.
For example in Windows there is a GetUserName function like this:
BOOL WINAPI GetUserName ( LPWSTR lpBuffer, LPDWORD nSize )

if you do this:
std::string str;

DWORD bufsize = 256;

GetUserName(str , &bufsize);

you get compile error:

error C2664: 'GetUserNameA' : cannot convert parameter 1 from 'class
std::basic_stri ng<char,struct std::char_trait s<char>,class
std::allocator< char' to 'char *'
No user-defined-conversion operator available that can perform
this
conversion, or the operator cannot be called
I suppose I could cast? But wondering what best way to tackle is.

I wonder if LPWSTR is, by chance, Microsoft gobbledygook for wide string?

Your question asked about a char* and char pointer points at a *byte*. So
all bets are off.

I get a headache just thinking about that crappy Microsoft stuff. If my
guess is right about the 'W', I guess the *right* way to proceed is to
fiddle with locales or facets or traits or some of that other high
faultin'
stuff. But that's not the way I would proceed. I would find out what that
damn acronym represented in the real world and convert/cast/whatever to
make
the thing work.
No I copied it wrong - should have been
BOOL WINAPI GetUserName ( LPSTR lpBuffer, LPDWORD nSize )
Jul 28 '07 #6
"Angus" writes:
No I copied it wrong - should have been
BOOL WINAPI GetUserName ( LPSTR lpBuffer, LPDWORD nSize )
Well, this works. I don't know what else to say. This is exactly what I
thought you meant when I read your first post.

----------------
#include <iostream>

#define STOP while(1) cin.get();

using namespace std;

char* foo()
{
return "hello";
}
//============
int main()
{
string s;
s = foo();
cout << s << endl;

STOP;
}
Jul 28 '07 #7

Angus <no****@gmail.c omwrote in message...
>
No I copied it wrong - should have been
BOOL WINAPI GetUserName ( LPSTR lpBuffer, LPDWORD nSize )

// includes here; <iostream>, <vector>, <cctype>, "windows.h" , etc.
{ // main() or ?
std::vector<cha rBuff( 100, '\0' );
DWORD DSize( static_cast<DWO RD>( Buff.size()-1 ) );
std::string User1;
if( GetUserName( &Buff.at(0), &DSize ) ){
std::cout<<"Get UserName()=";
for( std::size_t a(0); a < Buff.size(); ++a ){
if( not std::isprint( Buff.at(a) ) ){ break;} // <cctype>
std::cout<<Buff .at(a);
User1.push_back ( Buff.at(a) );
} // for(a)
} // if(Get)
else{
std::cout<<"Get UserName() FAILED"<<std::e ndl;
}
std::cout<<'\n' <<User1<<std::e ndl;
}

Clunky? Yup!!

If it doesn't work for you, post back with first 3 errors.

--
Bob R
POVrookie
Jul 28 '07 #8
On Jul 29, 2:18 am, "Angus" <nos...@gmail.c omwrote:
"osmium" <r124c4u...@com cast.netwrote in message

news:5h******** *****@mid.indiv idual.net...
"Angus" writes:
"osmium" <r124c4u...@com cast.netwrote in message
>news:5h******* ******@mid.indi vidual.net...
>"Angus" writes:
>I am working with a C API which often requires a char* or char buffer.
If
>a
C function returns a char* I can't use string? Or can I? I realise
I
can
pass a char* using c_str() but what about receiving a char buffer
into
a
string?
Reason I ask is otherwise I have to guess at what size buffer to
create?
And then copy buffer to a string. Doesn't seem ideal.
>One of the constructors for std::string will, in effect, accept a char*
>as
>an parameter.
>Thus:
>char* foo { /*stuff*/ }
>std::string s;
>s= foo();
>Or at least something similar to that.
For example in Windows there is a GetUserName function like this:
BOOL WINAPI GetUserName ( LPWSTR lpBuffer, LPDWORD nSize )
if you do this:
std::string str;
DWORD bufsize = 256;
GetUserName(str , &bufsize);
you get compile error:
error C2664: 'GetUserNameA' : cannot convert parameter 1 from 'class
std::basic_stri ng<char,struct std::char_trait s<char>,class
std::allocator< char' to 'char *'
No user-defined-conversion operator available that can perform
this
conversion, or the operator cannot be called
I suppose I could cast? But wondering what best way to tackle is.
I wonder if LPWSTR is, by chance, Microsoft gobbledygook for wide string?
Your question asked about a char* and char pointer points at a *byte*. So
all bets are off.
I get a headache just thinking about that crappy Microsoft stuff. If my
guess is right about the 'W', I guess the *right* way to proceed is to
fiddle with locales or facets or traits or some of that other high
faultin'
stuff. But that's not the way I would proceed. I would find out what that
damn acronym represented in the real world and convert/cast/whatever to
make
the thing work.

No I copied it wrong - should have been
BOOL WINAPI GetUserName ( LPSTR lpBuffer, LPDWORD nSize )
Even you can write this:

DWORD dwLen = 256;
std::string strUsername(dwL en '\0');
char* pData = const_cast<char *>(strUsername. c_str());
if (GetUserName(pD ata, &dwLen)
{
std::cout << "Get User name success." << strUsername;
}
else
{
std::cout << "Get user name failed"
}

This may work OK when strUsername is just a temporary variant, but
when copy a std::string to another std::string, it just increase it
reference counts and really did copy on changed.

When you wanted to call Windows API, just using CHAR and TCHAR, or
CString(if you application supports MFC), IMO, std didn't fill any
cases.

DWORD dwLen = 256;
CHAR* szUserName = new CHAR[dwLen]; //if GetUserName parameter is
LPWSTR, using TCHAR.
if (GetUserName(sz UserName, &dwLen) {
...
} else {
...
}

Jul 29 '07 #9
On 29 Jul, 13:57, "sss.z...@gmail .com" <sss.z...@gmail .comwrote:
Even you can write this:

DWORD dwLen = 256;
std::string strUsername(dwL en '\0');
char* pData = const_cast<char *>(strUsername. c_str());
if (GetUserName(pD ata, &dwLen)
:
This may work OK when strUsername is just a temporary variant, but
when copy a std::string to another std::string, it just increase it
reference counts and really did copy on changed.
No mays or buts, this is wrong. You can't go scribbling over
the value returned from c_str(). Even if it happens to work on your
compiler and standard library implementation today it may not
tomorrow.

When you wanted to call Windows API, just using CHAR and TCHAR, or
CString(if you application supports MFC), IMO, std didn't fill any
cases.

DWORD dwLen = 256;
CHAR* szUserName = new CHAR[dwLen]; //if GetUserName parameter is
LPWSTR, using TCHAR.
if (GetUserName(sz UserName, &dwLen) {
...
This is better, but if you're using a constant dwLen then
there's no point in dynamically allocating the buffer.
Note that according to MSDN the dwLen parameter is in/out,
so there's no risk of a buffer overflow here.

Jul 30 '07 #10

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

Similar topics

3
11183
by: Senthilraja | last post by:
I am able to compile the following code and get "hello" as ouput everytime I execute it:- #include <stdio.h> int main (void) { char *str; str="hello"; puts(str); return 0;
22
17157
by: spike | last post by:
How do i reset a string? I just want to empty it som that it does not contain any characters Say it contains "hello world" at the time... I want it to contain "". Nothing that is.. Thanx
35
2437
by: michael.casey | last post by:
The purpose of this post is to obtain the communities opinion of the usefulness, efficiency, and most importantly the correctness of this small piece of code. I thank everyone in advance for your time in considering this post, and for your comments. I wrote this function to simplify the task of combining strings using mixed sources. I often...
0
3923
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen. It is almost like it is trying to implement it's own COM interfaces... below is the header, and a link to the dll+code: Zip file with header,...
6
17159
by: ransoma22 | last post by:
I developing an application that receive SMS from a connected GSM handphone, e.g Siemens M55, Nokia 6230,etc through the data cable. The application(VB.NET) will receive the SMS automatically, process and output to the screen in my application when a message arrived. But the problem is how do I read the SMS message immediately when it arrived...
7
2942
by: fakeprogress | last post by:
For a homework assignment in my Data Structures/C++ class, I have to create the interface and implementation for a class called Book, create objects within the class, and process transactions that manipulate (and report on) members of the class. Interface consists of: - 5 private variables char author; char title; char code;
0
2056
by: Cause | last post by:
In the following code to call my website for serial registration reasons, I want to test on localhost. The code works on the internet, but this code sends me a bunch of 400 bad request errors when I use appache on port 80 localhost. Here's the code: ////////////////////////////////////////////////////////////////////////////////////// ...
41
2340
by: Dead Loop | last post by:
Hi all, I'm a beginner and my question is: Are there any differences between char *p = "Hello, world!"; and const char *p = "Hello, world!"; ?
9
3857
by: weirdwoolly | last post by:
Hopefully someone will be able to help. I have written a stored procedure in C++ called from a Java test harness to validate the graphic data types in C++ and their use. I have declared the vargraphic input parameters along the following lines in i_vargraphic100 vargraphic(100) and they are populated from String's in java.
0
7876
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...
0
8156
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. ...
0
8310
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...
1
7910
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...
0
8180
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...
0
5366
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...
0
3809
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...
1
2307
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
1
1409
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.