Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect two third party modules with "const char*" and "char*" arguments

Tags:

c++

I have two third party modules and I have to combine them. First I get data from a class. I will submit this data to a function.

bool loadLibrary(const char *strPlugName){
  HPLUGIN temp = _BASS_PluginLoad(strPlugName,0);
  return false;
}

The const char * strPlugName is a value that I got from another library. I cannot change this value type myself.

Inside the function I try to call a BASS Library function.

HPLUGIN temp = _BASS_PluginLoad(strPlugName,0);
Definition: typedef HPLUGIN (*BASS_PluginLoad_Type)(char *file,DWORD flags);

Here Xcode tell me:

Cannot initialize a parameter of type 'char *' with an rvalue of type 'const char *'

My question is how I can convert or cast this const char * to char *?

like image 501
pixbye Avatar asked Apr 02 '19 07:04

pixbye


2 Answers

If and only if the function called via _BASS_PluginLoad doesn't alter the memory pointed at by file, you can use a const_cast:

HPLUGIN temp = _BASS_PluginLoad(const_cast<char*>(strPlugName),0);

Some old c API's are not const correct on account of the const keyword being a fairly late addition to the C language. But they still don't mutate their arguments, so a const_cast is the easiest way to make use of them in const correct C++ wrappers. It's a perfectly legitimate reason (maybe even the reason) for that cast.

like image 161
StoryTeller - Unslander Monica Avatar answered Nov 16 '22 15:11

StoryTeller - Unslander Monica


The easy and safe way is to copy the argument into a local buffer, and then pass a pointer to that. As you are using C++, you can automate the memory management.

bool loadLibrary(const char *strPlugName){
  std::string local(strPlugName);
  local.push_back('\0'); // Ensure null terminated, if not using C++11 or greater
  HPLUGIN temp = _BASS_PluginLoad(&local[0],0);
  return false;
}

If using C++17, you can just call local.data() instead of &local[0].

Language lawyer caveat:

Strictly speaking, &local[0] was not defined to work in C++98 - in practice it always did (and later versions of the standard defined it to work).

like image 26
Martin Bonner supports Monica Avatar answered Nov 16 '22 16:11

Martin Bonner supports Monica