Global or pointer in managed C++ for customized class - arrays

My project has both managed & unmanaged code. I wrote a class cIVR in managed code, while defining it in an unmanaged cpp file. The project has been working fine for some time.
Now I need to call a member function of one of objects in array 'arrChannels' from another function in the same file.
During array definition it's not allowing me to declare as static due to managed code, so I want to pass a reference to my array in a global pointer so I can access member function throughout the file.
I am using .Net 2008.
main() {
array<cIVR^>^ arrChannels = gcnew array<cIVR^>(num_devices); //MAXCHAN
for(int i=0; i< num_devices; i++) { //MAXCHAN
arrChannels[i] = gcnew cIVR();
}
I want some thing like ->
cIVR *ch; //global
ch = arrChannels; //last in above code
func2(int index) {
ch[index]->setNumber("123");
}

Aside from the 'having a global is generally not a good idea issue', the place to correctly initialise ch would be inside main() after you created the array.
I'd also strongly recommend using the correct prototypes for the functions that you're using, for example:
int main()
and
void func2(int index)

Related

Create a array of shared_ptr with objects

I'm new to using smart pointers, I'm trying to create the same but I have errors.
class data{
private:
int ID;
public:
void setID(int a){
ID=a;
}
int getID(){
return ID;
}};
int main(){
data d*;
d=new data[30];
for(int i=0;i<30;i++){
(p+i)->setID(i);
}}
I try with:
shared_ptr<data> sp( new data[30]);
for(int i=0;i<30;i++){
sp->setID(i)[i];
}
Error:invalid types 'void[int]' for array subscript|
shared_ptr<data> sp( new data[30]);
for(int i=0;i<30;i++){
(sp+i)->setID(i);
}
Error: No match for 'operator+' (operand types are 'std::shared_ptr' and 'int')|
how can i do the same?
The issue is you're trying to add i to sp, instead of to the pointer that is managed by sp. What you want to do is use get() to get the stored pointer first:
for (int i = 0; i < 30; i++) {
sp.get()[i].setID(i);
}
If you use C++17, there's also operator[] which you could use.
However, you've got another problem (and operator[] wouldn't work because of it). You are storing the result of new[] in a std::shared_ptr which expects to manage a pointer returned by new. Your construction of sp should actually be:
std::shared_ptr<data[]> sp(new data[30]);
Otherwise you'll get undefined behavior, because sp is going to call delete on the address returned by new data[30], whereas it needs to use delete[]. Here's a bunch more info about the constructors of std::shared_ptr.
Side notes:
Please provide a minimal, complete, and verifiable example for your questions.
Are you sure you need std::shared_ptr? Won't std::unique_ptr work? std::unique_ptr is basically as fast as a raw pointer, whereas std::shared_ptr is slower.

Using hashmap in C to store String - Integer mapping once and use for entire program run

I have my own implementation of C hash_map_t struct that I can use as below?
// string value allocator
allocator_t *str_value_allocator;
allocator_init(&str_value_allocator, string_allocate_handler, string_deallocate_handler);
str_hash_map_init(&str_hash_map, str_value_allocator, 5);
str_hash_map_put(str_hash_map, test_key, test_val, strlen(test_val));
str_hash_map_get(str_hash_map, test_key, NULL)
str_hash_map_remove(str_hash_map, test_key)
str_hash_map_free(str_hash_map);
I would like to use this hash map in function like below:
void handle_keyboard_input(char **tokens, size_t num_tokens) {
char *virtual_key_name = strtok(tokens[1], " ");
size_t num_flags = 0;
char **modifier_flags = str_split(tokens[2], ", ", &num_flags);
// map virtual_key_name (char *) to virtual_key code (int)
// foreach modifier flag (char *) map to modifier flag code (int)
}
I can create 2 hash_maps for key_name -> key_code mapping and flag_name -> flag_code mapping. The problem is that I don't want to create this flag each time the request handler function is called but have only one data structure instance from first call of the function and in successive function invocations I want to reuse this data structure (data store) already created.
My hash_map is created on the heap so there isn't possibility to allocate it like the array somewhere inside library source code file.
In Java or even C++ I could create some Singleton pattern or static member but such concept is not available in C language. Probably I could create this hash_map at program startup somewhere at the beginning of program but how could I pass reference to library used by the program.
My recent idea was to use static hash_map_t variable inside my handle_keyboard_input function and somehow initialised it only when it is NULL (the first function call), and if variable isn't NULL in successive calls just reuse previously initialised hash_map_t structure.
What will be the best approach to this problem?
UPDATE
Could I use such code?
static str_hash_map_t *virtual_keys_map = NULL;
static str_hash_map_t *modifier_flags_map = NULL;
if (virtual_keys_map == NULL) {
virtual_keys_map_init(&virtual_keys_map);
}
if (modifier_flags_map == NULL) {
modifier_flags_map_init(&modifier_flags_map);
}
Since this appears to be a library, you have several options:
You can make your library more "object oriented" and force the user to do the proper instantiation. For example, you would have your ADT struct defined as KeyboardHandler, and then your handle_keyboard_input would look something like this instead:
void KH_handle_input(KeyboardHandler self, char **tokens, size_t num_tokens);
Which means the caller is now responsible for doing the instantiation of that single part:
// caller must get the ADT instance at some point, and you don't care when
KeyboardHandler kh = KH_init();
KH_handle_input(kh, some_tokens, num_tokens);
// some other part can be initialized later
MouseHandler mh = MH_init();
MH_handle_input(mh, some_tokens, num_tokens);
It's possible to create a library initializer for both Windows and POSIX dlls. So you can let this be done automatically instead.
Otherwise, it seems like you will have to make this "check" anytime your functions want to use this potentially-uninitialized hash tables (perhaps it's a single function, but anyway). In which case, I would at least refactor it into a separate function:
void handle_keyboard_input(char **tokens, size_t num_tokens) {
initialize_hashes_if_needed();
// ...and then the rest of the function
}
The reasoning is that you don't want to have to modify several functions if you decide there is something else that needs to be malloced.
Yes, code above cause that pointers will be initialised just once (or if you set them to NULL, condition will be true and it will init again) and stay in memory even if you get outside of function.
The lifetime of function static variables begins the first time the program flow encounters the declaration and it ends at program termination - in other words they are global variables.
Also the name of this variable is only accessible within the function, and has no linkage.
Still need to take great care if you think you need a globally-accessible variable. Read here.
static str_hash_map_t *virtual_keys_map = NULL;
static str_hash_map_t *modifier_flags_map = NULL;
if(virtual_keys_map == NULL) {
virtual_keys_map_init(&virtual_keys_map);
}
if(modifier_flags_map == NULL) {
modifier_flags_map_init(&modifier_flags_map);
}

How to manipulate the Global Variable in C

I have multiple void functions that relies on the each individual output of the functions since there are multiple variables (that are the same throughout the code), where each functions' output will be "stored" to them and be passed to another.
So, I decided to make those variables into global variables by making them static .... right after all the necessary #include... codes.
I was able to utilize all functions (14 functions in total,all void) by only calling four of them (Each functions, after processing its own function, passes the result into another function and after series of passing, only four of them are needed to be called in int main())
Now, I created another void function that requires the global variables as its parameter since that void function relies on the data that all the other functions "copied and put" into the global variables declared earlier. (Which I found is not working, since I heard that storing data into global variables is not possible.)
Can anyone teach me if there is any other way to create series of functions which requires output of each individual functions?
I checked if the variables were stored properly, so I tried using printf method right after the #3 process. I found out nothing gets printed when I expected a value from the struct data to be printed.
Ex:
typedef struct database{
//... variables
}data;
typedef struct itembase{
//... variables
}item;
static data user1;
static data user2;
static data *pointer[10000];
static item *pointer2[10000];
static item current[10000]; //Shares same value of the bracket with *pointer2
static data sectionA[1][10000];
static data sub_section[3][10000];
static int datacounter = 0; //..will be put inside the bracket of *pointer
static int itemcounter = 0; //..will be put inside the bracket of *pointer2
static int typenum = 0; ..will be put inside the first bracket of all the sections and subsections
static int section_count = 0; //..will be put inside the second bracket of all sections
static int sub_section_count[3] = {0}; //..will be put inside the second bracket of all sub_sections. The [3] will be the value of the typenum.
void load_data() // Accepts User's input and store them into struct data's variable using singly-linked list
{
//.... All data will be stored to *pointer[datacounter]
binarycheck(pointer[datacounter]->encoding,*pointer,datacounter);
//.... The `typedef struct` of data contains 12 variables. After storing 12 variables, datacounter will be ++ and the program will still continue to accept input from the user
}
void load_item()
{
//.... All item will be stored to *pointer2[itemcounter]
memcpy(&current[itemcounter],pointer2[itemcounter],sizeof(item));
}
void binarycheck(data encoding,data *pointer,int datacounter)
{
if ((encoding&128)==128){
typenum = 3;
memcpy(&sectionA[typenum][section_count],pointer,sizeof(data));
sub_sectionA[typenum][sub_section_count[typenum]] = sectionA[typenum[section_count];
section_count++;
sub_section_count++;
}
}
void askitem(data user)
{
// Tried putting `printf(" %s User1 Data#1",user1.firstdata);` and it works perfectly fine.
// Ask for user's selection on item
// If the item is found, then the content of that item will modify the data of the variable of `user`
}
void askinput(data user)
{
int whattype = 0;
int whatsub = 0;
printf("What type do you want?: \n);
scanf("%d",&whattype);
if (whattype == 1)
{typenum = 1;}
printf("What Sub type do you want?: \n);
scanf("%d",&whatsub);
if (whatsub == 1)
{ user = sub_sectionA[typenum][sub_section_count[typenum]];}
askitem(user);
}
void final_print(data user, data user2)
{
printf("%d\n",user.Adata);
printf("%d\n",user2.Adata);
}
int main()
{
load_data();
load_item();
askinput(user1);
//Tried putting `printf(" %s User1 Data#1",user1.firstdata);` but nothing shows.
askinput(user2);
//Nothing shows
final_print(user1,user2); //Nothing shows
}
Take a look at this function:
void askinput(data user)
Here you pass user by value to the function. When you pass by value, the function receives a copy of the variable. Changes that you make inside the body of that function only affect the copy. They are not visible to the caller's variable.
Instead you need to pass a reference. In C that means passing a pointer to a variable:
void askinput(data *user)
Inside the body of the function you need to de-reference the pointer to access members. So you use -> rather than . to refer to members.
And when you call the function you need to pass a pointer to the variable. So the call becomes:
askinput(&user1);
Frankly I do not understand why you are using global variables here at all. It's generally preferable to pass parameters otherwise you do find yourself struggling to keep track of which different version of the variable you are meant to be working on.
Finally, you have written your entire program and trying to debug this specific problem in the context of the entire program is confusing you. You really should have cut this down to a 10 or 20 line simple reproduction. Being able to do that in the future will make life much easier for you.

Experiment: Object Oriented C? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Can you write object oriented code in C?
Hi!
Just for the fun of it, I've been experimenting these last two days with creating a very simple, very straightforward object environment in pure C. I've been toying around with macros, dynamic linking, type-description structures and the like, and I've arrived at the following:
string_o str = new(String, "hello world");
list_o list = new(List);
List.pushf(list, str);
printf("In the list: \"%s\"\n",
String.text(List.popf(list)));
delete(list);
delete(str);
Looks and works kinda nice, but I can't figure a way to fake instance methods. I can't get past Class.function(instance), not without global macro replacements for function names, which defeats the purpose of encapsulation.
Again, this is an experiment, just for the challenge and the fun =). Can you guys help me figure out a way to do this? I don't want to use additional preprocessing, only plain C and GCC macros.
edit> forgot to say -- I don't want each instance to contain the function pointers in its structure. That would give me method syntax alright, but it would mean that a 4-byte data object would have a dozen function pointers copied over to each instance. That's kinda like cheating =P haha
Thanks in advance!
Object orientation in C is normally done with function pointers. That means a structure which contains not only the data for an instance but the functions to call as well.
It's the easiest way to do inheritance and polymorphism in C. By way of example, here's an object-orientd communications example.
It only has one method open but you can see how that differs for the TCP and HTML sub-classes. By having an initialisation routine which sets the a class-specific function, you get polymorphism.
#include <stdio.h>
// The top-level class.
typedef struct _tCommClass {
int (*open)(struct _tCommClass *self, char *fspec);
} tCommClass;
// Function for the TCP class.
static int tcpOpen (tCommClass *tcp, char *fspec) {
printf ("Opening TCP: %s\n", fspec);
return 0;
}
static int tcpInit (tCommClass *tcp) {
tcp->open = &tcpOpen;
return 0;
}
// Function for the HTML class.
static int htmlOpen (tCommClass *html, char *fspec) {
printf ("Opening HTML: %s\n", fspec);
return 0;
}
static int htmlInit (tCommClass *html) {
html->open = &htmlOpen;
return 0;
}
// Test program.
int main (void) {
int status;
tCommClass commTcp, commHtml;
// Same base class but initialized to different sub-classes.
tcpInit (&commTcp);
htmlInit (&commHtml);
// Called in exactly the same manner.
status = (commTcp.open)(&commTcp, "bigiron.box.com:5000");
status = (commHtml.open)(&commHtml, "http://www.microsoft.com");
return 0;
}
A more complete answer can be found here.
In response to your comment:
I don't want the functions contained in every single instance.
You're probably right. It's unnecessary to duplicate that information when it will be the same for every instance of a single class.
There's a simple way around that. Rather than having every instance carry its own set of function pointers, you create one structure holding them for the class, then each instance gets a pointer to that structure.
That will save quite a bit of space at the (minimal) cost of having to do two levels of indirection to call a function.

How to reset static variables within a function

Is there a way to reset variables declared as static within a function? The goal is to make sure that the function is not called with lingering values from an unrelated call. For example, I have a function opearting on columns of a matrix.
int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows
if (column != whichColumn){
memset(v,0,size);
whichColumn = which;
}
//do other things
}
The function is called n times, once for each column. Is this a proper way of "re-setting" the static variable? Are there other general fool-proof ways of resetting static variables? For example, I want to make sure that if the call is made with a new matrix with possibly different dimensions then the vector v is resized and zeroed etc. It seems the easiest way may be to call the function with a NULL pointer:
int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows
if (A == NULL){
FREE(v);
whichColumn = 0;
}
//do other things
}
Use an idempotent initializer function and global variables instead.
For example:
int foo;
int *m = NULL;
static void InitVars() {
foo = 0;
if (m != NULL) {
free(m);
}
m = malloc(sizeof(int)*5);
memset(m, 0, sizeof(int)*5);
}
If your initializer is really idempotent, you can call it again to reset the variables.
If you need this to be called automagically, use __attribute__((constructor)) (for GCC) like so:
static void InitVars __attribute__((constructor)) ();
However, you should note that if you need to do this, you should reconsider using in-function static variables and instead use passed-in fresh ones that are returned/written and passed to subsequent related calls.
I'd recommend turning it into a struct and writing a small helper function for managing the semantics of what you're trying to do. It could return the buffer if the request is appropriate for its size, or create a new one on demand (and free the old one) if necessary.
One approach I've seen used when a C module was imported to C++ was to surround the whole module with a class wrapper, and replace all static variables inside functions with uniquely-named "global" varaibles outside the functions. I don't know any good way to achieve a similar effect for projects involving multiple source files, though I'd like to know if one exists. I have some embedded system code in C, which I simulate by adding some C++ wrappers in VS2005. For example, I have I/O registers defined so that something like TX1CON = 0x5C; would translate into something like IOMAP(0x251).P = 0x5C; IOMAP is a property which would send "write 0x5C to address 0x251" to a hardware-simulation program. This approach works well, but I can't do a clean reset. Any ideas?
An approach which can sometimes be helpful if one needs a "reset" method which can hit an unknown number of functions or modules is to have a global counter for how many times that reset method has been called, and then have each function or module include code like:
extern unsigned long global_reset_count;
void do_something(int whatever)
{
static ... this, that, the other, etc. ...;
static unsigned long my_reset_count;
if (my_reset_count != global_reset_count)
{
my_reset_count = global_reset_count;
... initialize this, that, the other, etc ...
}
}
In some multi-threading contexts, if the initialization of the static variables may depend upon some global variables, one may wish to replace the "if" with a "while"; in such a case; memory barriers may also be needed in such a case, though the exact requirements would vary depending upon the operating environment.
Also, an alternative pattern that may be useful within embedded systems would be to have a modules_initialized global variable which gets set to 0 by the global reset method, and then have each module start with something like:
if (!atomic_bit_test_and_set32(&modules_initialized, FOOBOZZ_MODULE_ID))
{
... Initialize module FOOBOZZ ...
}
This would require that there be no more than 32 module ID's, and would require that they be uniquely allocated somehow, but some systems can handle that pretty nicely. For example, a linker may allow one to define a "data section" from address 0-31 of an address space independent from any other; if each module declares a single-byte variable within that address space, the linker could generate the appropriate addresses for those variables.
you could build your function in such a way that if you call it with zero parameters, then it will reset its internal static variables
here is an example :
int foo(matrix *A = NULL, int colnum = 0, int rownum = 0)
{
static int whichColumn;
static int *v; //vector of length A->nrows
if (A == NULL){
FREE(v);
whichColumn = 0;
}
//do other things
}
You actually just have to call function to reset like this:
foo(); // internal values would then be reset
Make sure that all your parameters to the function has default values, if for example you pass an optional, then make sure it has = boost::none as default value

Resources