Converting a String^ to a const void* in C++

1.1k views Asked by At

I am using C++/CLI to create a GUI that controls an external GPIB device. The GUI has a textbox where the user can enter a voltage. I am able to read the voltage from the textbox like this...

String^ v1 = textBox1->Text;

Assuming the user properly enters a decimal number into the textbox, I need to concatenate this value with some other text and produce a const void* to pass to the gpib library command.

So basically my question is how can I convert from String^ to const void*? I am able to convert String^ to a Double like this...

Double volt1 = Double::Parse(textBox1->Text);

So a solution for how to convert a Double to a const void* would work as well.

2

There are 2 answers

2
Jonathan Potter On

It's odd that your external library wants const void* and not a character pointer, but assuming it wants an ANSI string, you can use the marshal_context class to convert your String^ to a const char* pointer:

// marshal_context_test.cpp
// compile with: /clr
#include <stdlib.h>
#include <string.h>
#include <msclr\marshal.h>

using namespace System;
using namespace msclr::interop;

int main() {
   marshal_context^ context = gcnew marshal_context();
   String^ message = gcnew String("Test String to Marshal");
   const char* result;
   result = context->marshal_as<const char*>( message );
   delete context;
   return 0;
}

(Example code taken from here).

Of course if your library wanted a Unicode string you would use marshal_as<const wchar_t*> instead.

0
JohnnyW On

I was able to solve my problem with the following...

String^ v1 = textbox->Text;
Double volt1 = Double::Parse(v1);
std::string vt1 = std::to_string(volt1);
vt1 = "Volt1 " + vt1;
const void* vtg1 = vt1.c_str();

Probably not the most efficient way to solve the problem because I'm converting String^ to a Double to a std::string to a const void*, but it did solve my problem and I could not find a simpler way to do it which could be due to my lack of experience with CLI.