Const char* and char*


#1

I am using the Csound API which requires a char* filepath to compile a csound file.
I convert the string to a const char* using:

const char* caFilePath = sFilePath.toUTF8(); csound->Compile(caFilePath )

The problem is Csound won’t accept a const char* as a parameter, only a char*, is there a way to convert?


#2

const_cast <char*> (caFilePath)?


#3

Awesome, thanks.


#4

Are you sure the CSound function isn’t going to modify the contents of your string?

If it really is a read-only parameter, then it’s an absolutely shameful bit of programming for them not to make the parameter a const char*! You should write and tell them!


#5

I feel like the problems I’m having are very basic (apologies).

Csound takes a normal char* but the issue I have is getting a Juce String into a char*.
Is there a better way to do it than what I have below?

const char* chPath = sFPath.toUTF8(); chFilePath = const_cast <char*> (chPath);

chFilePath is a private char* member variable and I’m also getting a runtime access violation error on the second line of code.

Thanks


#6

You can use the CharPointer_UTF8::getAddress() method:

csound->Compile( const_cast<char*>(sFPath.toUTF8().getAddress()));

where sFPath is a Juce::String.


#7

Have a careful read of the comments for String::toUTF8() - it gives you a temporary pointer, don’t keep it in a member variable!


#8

Thanks Rory!

Unfortunately I still get an access violation error on this line:

that breaks to here:

/** Lets you access methods and properties of the object that this ScopedPointer refers to. */ inline ObjectType* operator->() const noexcept { return object; }


#9

The following works fine here:

String inputfile;
inputfile = “C:/MyDocuments/SourceCode/test/Builds/VisualStudio2010/Debug/test.csd”;
csCompileResult = csound->Compile(const_cast<char*>(inputfile.toUTF8()));


#10

Hmm, that gives me the following error:

“error C2440: ‘const_cast’ : cannot convert from ‘const juce::CharPointer_UTF8’ to 'char *'
1> Conversion requires a constructor or user-defined-conversion operator, which can’t be used by const_cast or reinterpret_cast”

with the inputFile String underlined.


#11

Have a careful read of the comments for String::toUTF8() - it gives you a temporary pointer, don’t keep it in a member variable![/quote]

I missed this earlier, thanks!