Click here to Skip to main content
15,883,829 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a C application.

I want to build an init function which creates handles to events which will be used outside the init function

Something like this:

InitEvents(HANDLE hEvent1, char *Event1Name, HANDLE hEvent2, char *Event2Name)
{
hEvent1 = CreateEvent(..Event1Name...);
hEvent2 = CreateEvent(..Event2Name...);
}

void main()
{
HANDLE h1,h2;

InitEvents(h1, "ONE", h2, "TWO");

SetEvent(hEvent1);
}

How can i pass the HANDLES by reference so the created handles will be available in the main function?

Thanks!

What I have tried:

Declaring the InitEvents(HANDLE *hEvent1.....)
hEvent1 = CreateEvent(..Event1Name...);
Posted
Updated 15-May-19 4:53am

This is C, not C# or C++: you don't have references - all parameters in C are passed by value (i.e. a copy of the variable content is passed to the function, not the variable itself).

To pass a "reference" you pass the address of the variable and receive it in the function as a pointer:
C++
void InitEvents(HANDLE* phEvent1 ...)
   {
   *phEvent1 = CreateEvent(...);
   ...
   }
void main()
   {
   HANDLE h1, h2;
   InitEvents(&h1, ....);
   ...
   }
 
Share this answer
 
Comments
dj4400 15-May-19 10:57am    
Thanks!
It worked well with handles but i also want to create a shared memory in the init function
which means that the Init function will look like this
InitEvents(HANDLE hEvent1, char *Event1Name, HANDLE hEvent2, char *Event2Name,
unsigned char* pSharedMemory, char* SharedMemName )
{
hEvent1 = CreateEvent(..Event1Name...);
hEvent2 = CreateEvent(..Event2Name...);
CreateSharedMemory(..SharedMemName ..);
}

void main()
{
HANDLE h1,h2;
unsigned char pBuf[1000];
InitEvents(h1, "ONE", h2, "TWO", pBuf, "SHARED");

SetEvent(hEvent1);
memcpy(pBuf,SomeData, DataLen);
}
I tried passing **char and calling Init with &pBuf
CPallini 15-May-19 13:41pm    
dj forgot to upvote your solution, have my 5.
You may also pass an array of struct to your InitEvents function, something like (but more robust)

C
typedef struct
{
  HANDLE handle;
  char * name;
} Event;


void InitEvents(Event event[], size_t event_count)
{ 
  event[0].handle = ...
  event[0].name = ...
  
  event[1].handle = ...
  event[1].name = ...
}

int main()
{

  Event event[2];


  InitEvents(event);

  //...
}
 
Share this answer
 
Comments
KarstenK 15-May-19 11:44am    
I would suggest a global struct, so it is visible in the whole code without fizzling.
CPallini 15-May-19 13:40pm    
Trust me, globals are bad.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900