I can't get this code to work...
typedef bool (* ProcessCallback)(DWORD ProcessId, DWORD ParentProcessId, TCHAR * Path, void * ImageBase, DWORD ImageSize);
bool EnumProcesses(ProcessCallback Callback);
// ---------
class cProcessList
{
public:
struct sProcess
{
DWORD ProcessId;
TCHAR Path[MAX_PATH];
};
std::vector<sProcess> List;
bool operator()(DWORD ProcessId, DWORD ParentProcessId, TCHAR * Path, void * ImageBase, DWORD ImageSize)
{
sProcess Process;
Process.ProcessId = ProcessId;
_tcsncpy(Process.Path, Path, _countof(Process.Path)-1);
Process.Path[_countof(Process.Path)-1] = _T('\0');
List.push_back(Process);
return false;
}
};
cProcessList Processes;
EnumProcesses(Processes); // Fails
/*
cannot convert parameter 1 from 'cProcessList' to 'ProcessCallback'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
*/
// ---------
bool CrapFunc(DWORD ProcessId, DWORD ParentProcessId, TCHAR * Path, void * ImageBase, DWORD ImageSize)
{
return false;
}
EnumProcesses(&CrapFunc); // Compiles ok
Output:
Line 1: error: typedef 'ProcessCallback' is initialized (use __typeof__ instead)
compilation terminated due to -Wfatal-errors.
EnumProcesses is not the psapi one, it's a wrapper for the toolhelp api. Yeah the name is misleading I guess, I don't include psapi.h so that's not the problem.
What EnumProcesses does, is call the provided callback for each process in the system.
I wanted to grab a list of processes in a vector so I wrote that class. I could have used a normal function (like Crapfunc demonstrates) but that would require a global vector and I don't like that too much (thread safety and whatnot :>).
I remember reading that overloading the () operator can be used for stuff that take function pointers. However, it doesn't compile :|
Can I even do it like that? I was told to take a look at how std::find_if does it but it uses a template that defines the callback param as a class which seems to work if you just give it a function address, since both function and class define operator().
I was rather looking for a way that would work with ordinary C...
Thanks for your help :)