using map in C++ and providing wrapper functions to use that in C -


in msvc6 need use map in c++ , provide wrapper functions use them in c add,delete , size. want without using classes in c++. used threads, each thread have structure handle have void * passed parameter c++ wrapper functions , want c++ code convert void * map , operations. not able convert void * map in c++ solution helpful.

i'm gonna give shot, because guessing:

i assume have function passed create thead function looking this:

int callback(void* userdata); 

so lets make callback function accessing map:

// in header file: "my_callback.h" first need declare function used c file, compiler name function according c standard , not c++. #ifdef __cplusplus extern "c" { #endif  // declare function: int my_callback(void * map_handle);  #ifdef __cplusplus extern "c" { #endif 

now, in c++ file make sure include headerfile:

#include "my_callback.h"  int my_callback(void * map_handle) {     // first, convenience, let define map type     using maptype = std::map<std::string, int>;      // first cast void * correct map * pointer     maptype *mapptr = static_cast<maptype*>(map_handle);      mapptr->insert( "test", 1 ); // insert     cout << (*mapptr)["test"];   // read      // or can assign reference hide away pointer syntax:     maptype & mapref = *static_cast<maptype*>(map_handle);       mapref.insert( "test", 1 ); // insert     cout << mapref["test"];   // read      // (...) } 

there few things worth noting:

  1. we allowed use static_cast because input void pointer should passing address of target map when create thread , statically casting , void pointer same type defined.

  2. this in no way thread-safe. special care has made when accessing the same resource multiple threads @ same time. if intend have 1 map , let threads access one, should include mutex ensure 1 thread accessing @ time. nifty way create small struct including map , mutex:

    struct map_n_mutex { maptype map; some_mutex_t mutex; // not sure correct type mutex on windows. };

in thread initialization phase:

// create map map_n_mutex user_data;  // create thread (i'm making function up, use have been using) create_thread( my_callback, &user_data); // pass pointer userdata 

if go approach, remember need cast map_n_mutex , not maptype inside callback function.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -