Create a __cdecl to __thiscall wrapper function on c++ - c++

I need to dynamically make a function that can be called by an external library using the __cdecl calling convention, and that then redirect the call to a method on a class, effectively serving as a proxy to a __thiscall calling convention.
The main idea is that this program (program1) should receive a function pointer from an external application (program2), package it into an object that can query us (program1) to know if the call to program2 should be made or not, then pass it to the library.
I have a vague idea of what a header for such class should look like
template <typename F, class C>
class this_call_wrapper
{
public:
// Creates a wrapper function that calls `operator()` on `object`
// `operator()` should take the same arguments as `F`
this_call_wrapper(const C* object);
// Deallocates memory used by this and the wrapper
~this_call_wrapper();
// Returns the pointer to the function wrapper
F* get_wrapper();
private:
C* object;
F* wrapper;
};
Are there any libraries out there that provide similar functionality? If not, how can I implement this in C++?

I found libffcall to be the most appropriate solution for these kind of problems. Constructing closures on assembly/machine code is also a valid option, but with how easy and portable it is to implement the same thing using libffcall, I don't think you'd want to mess with the former, unless you have some sort of (very restrictive) size constraint for your binaries.
This is the final solution.

Related

Calling c++ object in callback function of c library

I am using a C library, which uses callback functions.
Is there any way I can access calling object of C++ class ?
Edit:
I am using c-client lib.
Which have function mm_log.
void mm_log(char* string, long err_flag)
which is getting internally called by library. I want to check on which Imap stream it is getting called.
More Info
you can download library from ftp://ftp.cac.washington.edu/imap
All (good) C library functions that want a callback have a void* user_data pointer as part of the function and the callback parameter. You just pass a pointer to your object as this to the function and it just gets passed back to you in the callback. Example:
typedef void (*callback)(void*);
void dumb_api_call(callback cb, void* user_data){
cb(user_data);
}
struct Foo{};
void my_callback(void* my_data){
Foo* my_foo = static_cast<Foo*>(my_data);
}
int main(){
Foo my_foo;
dumb_api_call(my_callback, &my_foo);
}
If mm_log is a function which you are implementing and the library is calling (which is a terrible way for a library to do callbacks, by the way), then there is no way you can get it to reference a member function in your class.
What you could do is use a global variable which you set to point to your object before invoking the library (and clear after) and then use it within mm_log to invoke the desired method. This is nasty and dangerous but can work.
If you have more than one thread then exercise extreme caution - or find a better library.
Code is important for such a question. But without seeing any of your code, I can still give you a blanket statement :)
You'd have to wrap your C++ object with global functions that access a plain-old-struct, and export those with:
extern "C"
There are a plenty of caveats, but this is the gist of it.
See this FAQ: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html

c++ library with c interface

i need to write a library in c++ , usable by client to do some operations in a remote server. The only thing in the specific i haven't done yet it's: The c++ library need a C interface. Let me explain better:
From client using this lib i need to do call something like:
int operation(void* addr);
if int<0 error
and so..
But the library it's a class in c++.
So my answer is.. Need I a global variable holding the instance of class in the library?
The are some better option to develop this C interface of C++ class?
Thx in advice for answer.
You can use the PIMPL idiom in the C wrapper. You provide a method YourClass_Create that internally calls the constructor (using new) and returns the pointer to your class instance; for the client code this will be just an opaque handle (it may be a typedef for void *), to be passed to every function of your C interface to specify on which instance it has to work (just like FILE * in stdio).
All these functions will have to do is to call the corresponding method on the handle (converted back to a pointer to your class) and translate exceptions to error codes.
As #jdv-Jan de Vaan pointed out in his comment, don't forget the necessary #ifdefed extern "C" {} around your C wrapper code, otherwise you may get linker errors.

Sending parameters to a DLL to be boost::bind'ed

I have a DLL which has a function which accepts a function pointer converts it to a boost::function. This is then stored and then called from inside the DLL.
I want to add a function to the DLL to handle member functions in a similar way. I know I need to use boost::bind to wrap the member function pointer and the object together. I want to do the binding on the DLL side though so the EXE does not require boost libraries to be included.
How would you write this function? One which accepts a member function pointer and an object as arguments and binds them together.
Thanks!
you're warned by #Kylotan, so you can try something like this:
__declspec(dllexport) void store_mem_fn(void(Your_class::*mem_fn)(void), Your_class& instance)
{
std::vector<boost::function<void(void)> > container;
container.push_back(boost::bind(mem_fn, instance));
}
It might be a bad idea to try passing member function pointers into DLLs because they can vary in size depending on certain circumstances. (Some details here.) Maybe if you always know that you will be building both halves of the application with the same compiler you will be ok.
As for the function, I expect it would look something like this (completely untested and uncompiled code):
typedef void(ObjectType::*OTMemberFn)();
boost::function<void (ObjectType o)> bind_mem_fn(ObjectType o, OTMemberFn mf)
{
return boost::bind(mf, o);
}
Isn't Boost open source? If so, peek into the boost code, learn how it's done, and re-implement it yourself, without the dependency.

Python callback with SWIG wrapped type

I'm trying to add a python callback to a C++ library as illustrated:
template<typename T> void doCallback(shared_ptr<T> data) {
PyObject* pyfunc; //I have this already
PyObject* args = Py_BuildValue("(O)", data);
PyEval_CallObject(pyfunc,args);
}
This fails because data hasn't gone through swig, and isn't a PyObject.
I tried using:
swigData = SWIG_NewPointerObj((void*)data, NULL, 0);
But because its a template, I don't really know what to use for the second parameter. Even if I do hard code the 'correct' SWIGTYPE, it usually segfaults on PyEval_CallObject.
So my questions are:
Whats the best way to invoke swig
type wrapping?
Am I even going in the right
direction here? Directors looked
promising for implementing a
callback, but I couldn't find an
example of directors with python.
Update: The proper wrapping is getting generated. I have other functions that return shared_ptrs and can call those correctly.
My first answer misunderstood the question completely, so let's try this again.
Your central problem is the free type parameter T in the definition of doCallback. As you point out in your question, there's no way to make a SWIG object out of a shared_ptr<T> without a concrete value for T: shared_ptr<T> isn't really a type.
Thus I think that you have to specialize: for each concrete instantiation of doCallback that the host system uses, provide a template specialization for the target type. With that done, you can generate a Python-friendly wrapping of data, and pass it to your python function. The simplest technique for that is probably:
swigData = SWIG_NewPointerObj((void*)(data.get()), SWIGType_Whatever, 0);
...though this can only work if your Python function doesn't save its argument anywhere, as the shared_ptr itself is not copied.
If you do need to retain a reference to data, you'll need to use whatever mechanism SWIG usually uses to wrap shared_ptr. If there's no special-case smart-pointer magic going on, it's probably something like:
pythonData = new shared_ptr<Whatever>(data);
swigData = SWIG_NewPointerObj(pythonData, SWIGType_shared_ptr_to_Whatever, 1);
Regardless, you then you have a Python-friendly SWIG object that's amenable to Py_BuildValue().
Hope this helps.
shared_ptr<T> for unknown T isn't a type, so SWIG can't hope to wrap it. What you need to do is provide a SWIG wrapping for each instance of shared_ptr that you intend to use. So if for example you want to be able to doCallback() with both shared_ptr<Foo> and shared_ptr<Bar>, you will need:
A wrapper for Foo
A wrapper for Bar
Wrappers for shared_ptr<Foo> and shared_ptr<Bar>.
You make those like so:
namespace boost {
template<class T> class shared_ptr
{
public:
T * operator-> () const;
};
}
%template(FooSharedPtr) boost::shared_ptr<Foo>;
%template(BarSharedPtr) boost::shared_ptr<Bar>;

If classes with virtual functions are implemented with vtables, how is a class with no virtual functions implemented?

In particular, wouldn't there have to be some kind of function pointer in place anyway?
I think that the phrase "classes with virtual functions are implemented with vtables" is misleading you.
The phrase makes it sound like classes with virtual functions are implemented "in way A" and classes without virtual functions are implemented "in way B".
In reality, classes with virtual functions, in addition to being implemented as classes are, they also have a vtable. Another way to see it is that "'vtables' implement the 'virtual function' part of a class".
More details on how they both work:
All classes (with virtual or non-virtual methods) are structs. The only difference between a struct and a class in C++ is that, by default, members are public in structs and private in classes. Because of that, I'll use the term class here to refer to both structs and classes. Remember, they are almost synonyms!
Data Members
Classes are (as are structs) just blocks of contiguous memory where each member is stored in sequence. Note that some times there will be gaps between members for CPU architectural reasons, so the block can be larger than the sum of its parts.
Methods
Methods or "member functions" are an illusion. In reality, there is no such thing as a "member function". A function is always just a sequence of machine code instructions stored somewhere in memory. To make a call, the processor jumps to that position of memory and starts executing. You could say that all methods and functions are 'global', and any indication of the contrary is a convenient illusion enforced by the compiler.
Obviously, a method acts like it belongs to a specific object, so clearly there is more going on. To tie a particular call of a method (a function) to a specific object, every member method has a hidden argument that is a pointer to the object in question. The member is hidden in that you don't add it to your C++ code yourself, but there is nothing magical about it -- it's very real. When you say this:
void CMyThingy::DoSomething(int arg);
{
// do something
}
The compiler really does this:
void CMyThingy_DoSomething(CMyThingy* this, int arg)
{
/do something
}
Finally, when you write this:
myObj.doSomething(aValue);
the compiler says:
CMyThingy_DoSomething(&myObj, aValue);
No need for function pointers anywhere! The compiler knows already which method you are calling so it calls it directly.
Static methods are even simpler. They don't have a this pointer, so they are implemented exactly as you write them.
That's is! The rest is just convenient syntax sugaring: The compiler knows which class a method belongs to, so it makes sure it doesn't let you call the function without specifying which one. It also uses that knowledge to translates myItem to this->myItem when it's unambiguous to do so.
(yeah, that's right: member access in a method is always done indirectly via a pointer, even if you don't see one)
(Edit: Removed last sentence and posted separately so it can be criticized separately)
Non virtual member functions are really just a syntactic sugar as they are almost like an ordinary function but with access checking and an implicit object parameter.
struct A
{
void foo ();
void bar () const;
};
is basically the same as:
struct A
{
};
void foo (A * this);
void bar (A const * this);
The vtable is needed so that we call the right function for our specific object instance. For example, if we have:
struct A
{
virtual void foo ();
};
The implementation of 'foo' might approximate to something like:
void foo (A * this) {
void (*realFoo)(A *) = lookupVtable (this->vtable, "foo");
(realFoo)(this); // Make the call to the most derived version of 'foo'
}
The virtual methods are required when you want to use polymorphism. The virtual modifier puts the method in the VMT for late binding and then at runtime is decided which method from which class is executed.
If the method is not virtual - it is decided at compile time from which class instance will it be executed.
Function pointers are used mostly for callbacks.
If a class with a virtual function is implemented with a vtable, then a class with no virtual function is implemented without a vtable.
A vtable contains the function pointers needed to dispatch a call to the appropriate method. If the method isn't virtual, the call goes to the class's known type, and no indirection is needed.
For a non-virtual method the compiler can generate a normal function invocation (e.g., CALL to a particular address with this pointer passed as a parameter) or even inline it. For a virtual function, the compiler doesn't usually know at compile time at which address to invoke the code, therefore it generates code that looks up the address in the vtable at runtime and then invokes the method. True, even for virtual functions the compiler can sometimes correctly resolve the right code at compile time (e.g., methods on local variables invoked without a pointer/reference).
(I pulled this section from my original answer so that it can be criticized separately. It is a lot more concise and to the point of your question, so in a way it's a much better answer)
No, there are no function pointers; instead, the compiler turns the problem inside-out.
The compiler calls a global function with a pointer to the object instead of calling some pointed-to function inside the object
Why? Because it's usually a lot more efficient that way. Indirect calls are expensive instructions.
There's no need for function pointers as it cant change during the runtime.
Branches are generated directly to the compiled code for the methods; just like if you have functions that aren't in a class at all, branches are generated straight to them.
The compiler/linker links directly which methods will be invoked. No need for a vtable indirection. BTW, what does that have to do with "stack vs. heap"?