Reputation: 3
I have a problem using a C library in C++. I fear that the solution is very easy but I am to stupid to get it.
The library defines the function like this:
CAENHVLIB_API CAENHVRESULT CAENHV_GetChName(int handle, ushort slot,
ushort ChNum, const ushort *ChList, char (*ChNameList)[MAX_CH_NAME]);
In the example it is called like this:
char (*listNameCh)[MAX_CH_NAME];
// ... leaving out the other lines since they are not the problem ...
listNameCh = malloc(MAX_CHANNELS*MAX_CH_NAME);
ret = CAENHV_GetChName(handle, slot, NrOfCh, listaCh, listNameCh);
So now the problem. In C++ I am not able to use the malloc(MAX_CHANNELS * MAX_CH_NAME) because I cant cast it correctly. It works with "-fpermissive"-Flag but I would like to do it without such a hack.
Somebody has an idea how to get around this?
Cheers
Upvotes: 0
Views: 160
Reputation: 206557
You can use either malloc
or new
. If you use malloc
, you have to cast the returned value. If you use new
, you don't have to cast.
listNameCh = (char (*)[MAX_CH_NAME])malloc(MAX_CHANNELS*MAX_CH_NAME);
or
listNameCh = new char[MAX_CHANNELS][MAX_CH_NAME];
Upvotes: 2
Reputation: 67713
Well, you can probably cast it correctly to avoid the -fpermissive
.
One one level this isn't a hack - C and C++ have different rules for implicit casting here. If you insist on writing C in C++, you'll need the occasional cast to make it work.
On another level, the problem is that you're writing C and compiling it as C++. It would be better to either
std::array<char[MAX_CH_NAME], MAX_CHANNELS>
and it will take care of the allocation for you
std::vector<char[MAX_CH_NAME]>
similarly if you want to re-size itUpvotes: 3