iRegistry
iRegistry

Reputation: 3

C library in C++

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

Answers (2)

R Sahu
R Sahu

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

Useless
Useless

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

  1. re-write it as good, idiomatic C++. You should be able to use std::array<char[MAX_CH_NAME], MAX_CHANNELS> and it will take care of the allocation for you
    • or you can use std::vector<char[MAX_CH_NAME]> similarly if you want to re-size it
  2. re-write it as less-good C++, with explicit new/delete instead of malloc/free (new expressions are strongly-typed and don't need casting)
  3. write your C code in a C-language module, exposing some sane interface, and then call it from C++

Upvotes: 3

Related Questions