Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

HELP!!! How to convert BSTR type to char* 1

Status
Not open for further replies.

nhungr

Programmer
Jan 31, 2005
26
CA
I have a BSTR type variable (passed in from a Visual Basic application) that I'm trying to convert into a char* so that I can use it in an iostream. For some reason, the conversion function that I'm using only converts every SECOND character of the BSTR variable to the char variable. For example, if I have:

BSTR a = "anystring";
char* c;
c = BSTRtoChar(a);

then I get c = "aytig". Why?????? Here is my full code:

Code:
void __declspec(dllexport) CALLBACK myfunction(BSTR mybstr)
{
	int n;
	char* mychar;

	n = SysStringLen(mybstr); [COLOR=green]// length of input string[/color]
	mychar = (char*) malloc(n+1); [COLOR=green]// allocate space to character array[/color]
	[b]mychar=BSTRtoChar(mybstr);[/b]	[COLOR=green]// Convert VB string to C++ char array.[/color]

	ifstream infile1(mychar);
	
	...etc...
}

[COLOR=green]// BSTR to Char conversion function:[/color]
char* BSTRtoChar(BSTR String)
{
    int n, i;
    char* FinalChar;
    n = SysStringLen(String); [COLOR=green]// length of input[/color]
    FinalChar = (char*) malloc(n+1);
    for (i = 0; i < n; i++)
    {
		FinalChar[i] = (char) String[i];
    }
    FinalChar[i] = 0;
    return FinalChar;
}

 
MSDN:
In 32-bit OLE, BSTRs use Unicode like all other strings in 32-bit OLE.
...
Win32 provides MultiByteToWideChar and WideCharToMultiByte to convert ANSI strings to Unicode, and Unicode strings to ANSI.


See WideCharToMultiByte() description and samples in MSDN (there are lots of parameters)...
 
Thank you very much for the explanation. That was my problem: the wide strings versus the narrow strings. I ended up just scrapping most of the above code and using this MUCH simpler version instead:

Code:
void __declspec(dllexport) CALLBACK myfunction(BSTR mybstr)
{
    LPSTR mychar; // narrow string
    mychar = (LPSTR) mybstr;

    ifstream infile1(mychar);
    
    ...etc...

}

And it works!!!! Simple, simple, simple. Always simple. Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top