1
votes

I am trying to create a shared library to expose some of the c++ methods.

I simply create a wrapper in which i expose methods as C functions using extern "C" linkage.

Within the corresponding C function i create a object of the class and call the appropriate method.

The issue i have is some of the methods that needs to be exposed use templates as arguments.

E.g. : C++ :

class myclass {
    template <typename T>
    void write(int addr, T data);
    void get_data()
}

C wrapper:

void get_date() {
    myclass obj;
    obj.get_data();
}

how should i expose the other method ?

  1. can i use typeid operator in the C wrapper function to determine the type of argument ?
  2. any other better ideas on this ?
1
templates aren't part of C - please only use relevant tags. - dave

1 Answers

3
votes

You're kind of stuck since C doesn't support templates or typeid.

The best/simplest way that I can think of is to create a version of the C function for each argument type you wish to use.

void write_int( int i )
{
  myclass obj;
  obj.write(i);
}

void write_string( char * s )
{
  myclass obj;
  obj.write(s);
}

Another option might be to switch on type and pass a void* pointer.

void write( int type, void* ptr )
{
   myclass obj;
   switch(type)
   {
      case C_INT:
        obj.write( *static_cast<int*>(ptr) );
        break;
      case C_STR:
        obj.write( *static_cast<char**>(ptr) );
        break;
      default:
        //Some kind of error.
   }
}

A final option would be to do some trickery using a var args function:

void write( int type, ... )
{
   va_list argp;
   va_start( argp, type);
   myclass obj;
   switch(type)
   {
      case C_INT:
        obj.write( va_arg(argp, int) );
        break;
      case C_STR:
        obj.write( va_arg(argp, char* ) );
        break;
      default:
        //Some kind of error.
   }
}

You can detect some usage errors in this by defining a macro that hides the function :

#define write(X,Y) write(X,Y)

This means that usages with the wrong number of arguments should generate an error.