Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3675
  • Last Modified:

Conversion of String^ to const char* in C++/CLI

Hello,

I am trying to figure out how to convert a variable of type String^ to a const char* in C++/CLI.

I tried this, but it doesn't seem to do the job:

array<Char>^ inputFile = inputFileName->ToCharArray();

Thanks,
Zayn            
0
Zaynul
Asked:
Zaynul
  • 2
2 Solutions
 
Daniel Van Der WerkenIndependent ConsultantCommented:
I might not be understanding this issue:

      System::String ^inputFileName = gcnew System::String("AFileName.TXT");

      array<System::Char> ^inputFile = inputFileName->ToCharArray();

Works for me.  What exacly is "doing the job" here?

---Dan---
0
 
ZaynulAuthor Commented:
Sorry, what I meant was that that statement compiles, but I need "inputFile" to be of type const char* because I need to pass it into a C++ method that takes a const char* as a parameter.  When I run the following code:
------------------------------------------------------------------------------------------------------------------------------
String^ inputFileName = "blahblah";
String^ outputFileName = "yadayada";

array<Char>^ inputFile = inputFileName->ToCharArray();
array<Char>^ outputFile = inputFileName->ToCharArray();

myObject->PerformScan(inputFile, outputFile);

//PerformScan is defined like this: PerformScan(const char *originalFileName,  const char *outputFileName)
---------------------------------------------------------------------------------------------------------------------------
I get the error below:

Error      2      error C2664: 'MyClass::PerformScan' : cannot convert parameter 1 from 'cli::array<Type> ^' to 'const char *'      ...


Thanks Dan.

Zayn
0
 
AlexFMCommented:
String^ inputFileName = "blahblah";

IntPtr ptr = Marshal::StringToHGlobalAnsi(inputFileName);

UnmanagedFunction((char*)ptr.ToPointer());

Marshal::FreeHGlobal(ptr);
0
 
ZaynulAuthor Commented:
Thanks AlexFM.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now