I have a dll which requires me to set a callback function for it (actually it's a camera sdk and it will callback my function when it receives a picture).
I want to have multiple (user input) cameras but I can't.
Since I should make unknown number of callback functions.
The easy way is to make a class (camera) which have a function for its callback.
but I cannot pass the pointer of member of the class to the dll (it only accept (void)(image*))
Any possible solution?
Try creating a global list of all the function objects to be called, then add a single function that calls each of the callbacks with the required data. Something like this:
std::vector<ICallback*> g_callbacks;
void callback_wrapper( image * image )
{
for(unsigned int i=0; i<g_callbacks.size(); ++i)
{
g_callbacks[i]->process( image );
}
}
Then you set the callback used by the SDK to the callback_wrapper function.
Depending on the OS, you may be able to create dynamic functions for each callback object. I've done exactly that for callbacks from legacy code which didn't have any facility to pass a value to the callback.
Create a small prototype forwarding function with the type the library expects which then calls the real callback function with an easily seen extra parameter
void Call01020304 () {
CallWithValue(0x01020304);
}
Compile it and look at the hex for the assembly. It should be obvious where the constant is.
You then use VirtualAlloc + PAGE_EXECUTE_READWRITE or mmap + PROT_EXEC to allocate some memory which can be executed. Allocation is usually in 4K blocks, so create a class to manage the functions, as you will be allocating enough for many in one go.
When you need a new callback function with a unique value, copy the bytes of the prototype with appropriately changed value into your executable memory, and return the pointer to it as the callback function.
Does camera SDK support multiple cameras connection? If not, you need to talk with SDK provider.
If SDK supports multiple connection, it must provide the way to recognize the camera in callback function. But actual answer is in SDK itself. What is the "image" type, maybe it contains camera ID? Maybe camera ID is supplied when a client code makes callback subscription? Something like this:
void Callback0(image*);
void Callback1(image*);
SubscribeImageCallback(0, Callback0); // camera 0
SubscribeImageCallback(1, Callback1); // camera 1
Actual answer to your question depends on the camera SDK interface.
Related
Im trying to hook the ID3D12GraphicsCommandList::CopyTextureRegion method with MinHook but the problem is that the method is inside ID3D12GraphicsCommandList which makes it hard to hook.
Here is my current approach which unfortunatley is 0
// not working, CopyTextureRegionHook is 0
auto CopyTextureRegionHook = GetProcAddress(GetModuleHandleA("d3d12.dll"), "CopyTextureRegion");
MH_CreateHook(reinterpret_cast<void**>(CopyTextureRegionHook), &HK_CopyTextureRegion, reinterpret_cast<void**>(&oCopyTextureRegion));
MH_EnableHook(CopyTextureRegionHook);
Hooking methods like D3D12CreateDevice, D3D12CoreRegisterLayers.. work because they are not in a interface like ID3D12GraphicsCommandList
How would I properly hook CopyTextureRegion?
Because you're dealing with an interface, you won't be able to hook the function directly in memory since it's dependent on the pointer to the interface. In which case you have to utilize a technique called VMT(Virtual Method Table) hooking. In order to achieve this, you'll need to be able to retrieve the pointer to the interface in memory, then locate the virtual method table index(offset) of the function pointer. Which then you'll have to overwrite with your own function address. Your hooked function will have to comply with the calling convention of the original.
I am currently creating my own GUI-Library based on SFML.
At the moment i am working on a Button. So when creating a button you also have to specify a callback which is a function, executed on the button click.
Now, I'm answering me what the disadvantages are of using just a pointer to a function as a button-callback, because I don't know any popular GUI-Library doing it so simply, too.
If the callback function is a long process, I would execute it in a new thread, but i'm not sure about that in the moment.
So, what would be reasons, not to use such simple solution and especially, what would be a better way?
It's a tricky problem!
Function pointers are simple to implement on the sender side, but they are difficult to use on the receiver side because they they don't have any context.
One issue is that a function pointer cannot point to a member function. That's why you often see (C-style) frameworks pass an arbitrary void *userData to their callbacks, so you can cast your this pointer and retrieve it in that way. This still needs you to write a static wrapper function to cast the pointer back and call the member function.
A more modern solution would be to use std::function. This can contain a regular function pointer, a member function pointer, but also a lambda or a functor.
However, when you add context like this (or in some other way), you quickly run into difficulties with lifetimes. When the receiving class is destroyed before the sender, what is supposed to happen? If you don't do anything, this situation will result in undefined behaviour. A solution is to track on the receiver side to which events the receiver is subscribed, and unbind them before the receiver is destroyed. And this needs to be done in both directions: when the sender is destroyed, it also needs to notify the receiver that it should forget about the sender, otherwise the receiver would later try to unbind an event that no longer exists.
And I haven't even begun to think about multithreading yet...
There are libraries that solve these problems in various ways, for example eventpp (just found through a web search, this is not an endorsement).
Another one to mention would be the Qt toolkit, which went so far as to write their own small signals and slots extension to the C++ language (implemented as a code generator and a pile of macros) to solve this problem in a very ergonomical way.
what the disadvantages are of using just a pointer to a function as a button-callback
Passing some context argument to that function would come handy.
I mean, the UI may have a lot of buttons performing the same action on various objects. Think maybe of "send message" button next to each nick in a friend list.
So you may want your buttom to pass some context arguments to the call.
But since we're talking C++, this'd better be abstracted as
struct IButtonAction
{
virtual void OnAttached() = 0;
virtual void OnDetached() = 0;
virtual void OnClick() = 0;
};
And let the client code implement this interface storing whichever Arg1, Arg2, etc in each instance object.
The button class would call OnAttached/OnDetached when it begins/ends using the pointer to an instance of this callback interface. These calls must be paired. Client implementation of these methods may perform lifetime management and synchronization with OnClick, if required.
OnClick method performs the action.
I don't think the button should bother with threads. It's the responsibility of the client code to decide whether to spawn a thread for a lengthy action.
I’m trying to store an object passed from JavaScript to a Node.js Addon in a void *. I can’t seem to get this to compile; building with node-gyp produces error: no matching function for call to 'Cast'.
The long version of what I’m trying to do is write a Node.js Addon that runs Csound. Csound works, from a bird’s-eye view, with C functions that take a pointer to an opaque Csound struct as (usually) the first argument. This struct contains a void * to “hostData”, arbitrary data set by a program hosting Csound. Some things that Csound does, like posting messages, are modified with callbacks—function pointers in this case. I need a place to store callbacks for each instance of Csound, so I’m trying to let someone set hostData to an object from JavaScript, but I also want to set the callbacks for a Csound instance as hidden properties on this hostData object.
I think the code will need to look something like
#include "csound.h"
#include <node.h>
static void CsoundMessageCallback(CSOUND *Csound, int attributes,
const char *format, va_list valist)
{
// Call the JavaScript function we stored in the hostData of Csound.
}
static void _wrap_csoundSetMessageCallback(
const v8::FunctionCallbackInfo<v8::Value>& args)
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
CSOUND *Csound;
// Pretend we get the Csound instance from args[0] here. This is actually done
// by SWIG <http://www.swig.org>.
// This does not compile. csoundGetHostData() returns a void *, but I’m assuming
// hostData was set to an object from JavaScript.
v8::Persistent<v8::Object> hostData =
v8::Persistent<v8::Object>::Cast(csoundGetHostData(Csound));
hostData.SetHiddenValue(
v8::String::New("CsoundMessageCallback"),
v8::Persistent<v8::Function>::Cast(args[1])
);
csoundSetMessageCallback(Csound, CsoundMessageCallback);
}
I’m guessing I need to take a close look at V8’s internal fields, but I’m really not sure.
Typically what I've done in situations like this is I write a wrapper C++ class (inheriting from node's ObjectWrap class) that stores a pointer to the instance of whatever C/C++ class I'm wrapping and has various public methods to interact with that instance.
When new is called from JS land, a new instance of the wrapper C++ class gets created and associated with the new JS object. Then you have JS functions that kick off whatever async tasks that utilize the wrapped library's callbacks.
From there it's just a matter of calling uv_async_send() from the wrapped library's callbacks to signal the main thread and then calling the JS callback from the uv_async callback.
You can see an example of all of this here (especially in the Windows-specific parts):
The Pcap class holds a pcap_t pointer (would be a CSOUND pointer for you).
When a new Pcap is created from JS land, I wrap a new C++ class instance.
Initialize a uv_async_t which sets up the callback to fire on uv_async_send() and also associates the user data pointer to the class instance for easy access. You could do this initialization during the call to new if you wanted, instead of a separate prototype function (open()) like I have done since initialization just happens once.
Then from the wrapped library's callback, I signal the main thread.
From the uv_async callback, I can then access the wrapper class instance and use V8 functions safely. Although in my particular case, I have another callback which uses V8 functions. However you can use them safely inside your uv_async callback.
As far as storing JS callbacks goes, there are different ways to handle that. One solution might be to create a baton object that stores a Persistent copy of the JS callback and the wrapper class instance and store that baton in uv_async_t's user data pointer. This would mean creating a new uv_async_t for every request (which is different than the example I gave above).
My code calls a function from 3rd party library. Let's call this function SomeFunc
void SomeFunc(void (*callBack) (int));
As you can see SomeFunc takes a callback function parameter. Once SomeFunc is called, the calling thread will progress, and the library will execute the callback several time on a different thread -- passing it different status code.
My requirement is the thread that calls SomeFunc (aka main thread) should wait until certain status code is passed to the callback. So far I have something like this
CEvent *pEvt = NULL;
void myCallBack(int code) {
if(code == SOME_MAGIC_NUM) pEvt->SetEvent(); // signal thread waiting for this event obj they can continue
}
int main (int argc, char** argv) {
pEvt = new CEvent(FALSE, TRUE);
SomeFunc(myCallBack); // This doesn't block, main thread will progress to next line
WaitForSingleObject(pEvt, 5000); // wait here until 3rd party library call myCallBack with code SOME_MAGIC_NUM -- or if it doesn't after 5 seconds, continue
// do interesting stuff here..
return EXIT_SUCCESS;
}
Now this seem fine if I only do this on the main thread / main function like above. However if multiple thread can execute the code block in main above, my problem is they will share reference to the global pEvt variable, and it will mess up
What's the best code design approach I should take here? Ideally I would like to change the callback function signature to accept reference to the CEvent object, but since it's a 3rd party library I'm unable to do that.
You really want the equivalent of a closure in javascript. You can accomplish something similar by binding the function call to a new CEvent object every time. Take a look at std::bind1st or boost::bind.
See also this stackoverflow thread
You can only achieve this is the 3rd party provides a way to pass back a 'custom' argument to the callback. Well designed APIs allow to set up a callback and a void* value and the callback receives this argument when invoked. From this void* you can expand to anything you like, including objects and method calls, via unsafe casting. All solutions based on binding or member function address or whatever else ultimately boil down to the same issue: somehow the this* has to be passed back to the callback.
For an example, see BIO_set_callback: it allows you to set the callback and a callback arbitrary argument. Note that the callabck argument can be indirect, like for example in gnutls: the argument can be set as arbitrary data on the session via gnutls_session_set_ptr and then in the callback(s) it can be retrieved using gnutls_session_get_ptr. Your 3rd party may provide such an indirect method.
If the library does not offer such feature then you're stranded into hacks. For example you can have a collection of callbacks 'available', each one associated with a specific event (ie. different functions as address, although same code). You pick one callback and remove it from collection and place it, then wait for the event associated with that callback. When done, place the callback back into the available list. The size of the 'available' list is hard coided at compile time as you really need separate functions, one for each callback.
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do.
If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not (void*, char*, int*, etc...)
I.e if I define a function prototype like:
typedef void (__cdecl *testFunc_t)(int* pData);
I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an stdcall or _cdecl call.
The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product.
Here is my plan:
Create a thread in the remote process using CreateRemoteThread at the origin of the function want to call, though I would do so in a suspended state.
I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call ExitThread(eax) - as this would exit the thread with the function's return value - I would then recover this by by using GetExitCodeThread
I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments.
Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code.
I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school.
The question:
If I have a function prototype such as
typedef void (__cdecl testFunc_t)(int pData);
Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int*) If, for example, I have a function like:
template<typename T> unsigned long getPrototypeArgLength<T>()
{
//would return size of arguments described in the prototype T
}
//when called as
getPrototypeArgLength<testFunc>()
This seems like quite a school project...
For step 3 you can use ReadProcessMemory / WriteProcessMemory (one of them). For example, the new thread could receive the address (on the calling process), during the thread creation, of the parameters on the start (begin and end). Then it could read the caller process memory from that region and copy it to its own stack.
Did you consider using COM for this whole thing? you could probably get things done much easier if you use a mechanism that was designed especially for that.
Alright, I figured out that I can use the BOOST library to get a lot of type information at compile-time. Specifically, I am using boost::function_traits however, if you look around the boost library, you will find that you can recover quite a bit of information. Here's a bit of code I wrote to demonstrate how to get the number of arguments of a function prototype.
(actually, I haven't tested the below code, its just something I'm throwing together from another function I've made and tested.)
template<typename T>
unsigned long getArgCount()
{
return boost::function_traits<boost::remove_pointer<T>::type>::arity;
}
void (*pFunc)(int, int);
2 = getArgCount<BOOST_TYPEOF(pFunc)>();