Swig C++ Lua Pass class by reference - c++

I don't know why I'm having a hard time with this. All I want to do is this:
class foo {
public:
foo(){}
~foo(){}
float a,b;
};
class foo2 {
public:
foo2(){}
foo2(const foo &f){*this = f;}
~foo2(){}
void operator=(const foo& f){
x = f.a;
y = f.b;
}
float x,y;
};
/* Usage(cpp):
foo f;
foo2 f2(f);
//or using the = operator
f2 = f;
*/
The problem I'm having is that, after swigging this code, I can't figure out how to make the lua script play nice.
/* Usage(lua)
f = example.foo()
f2 = example.foo2(f) --error
*/
The error I get is "Wrong arguments for overloaded function 'new_Foo2'":
Possible c/c++ prototypes are:
foo2()
foo2(foo const &)
The same thing happens if I try and use do f2 = f. As I understand it everything is stored as a pointer so I did try adding an additional constructor that took a pointer to foo but to no avail.

In the copy constructor you have the reference operator in the wrong place, put it after 'foo'. As your code stands it doesn't compile, at least not for me on VS 2008.
Edit: I see, thanks for the update. Well I'm not particularily familiar with LUA, but I know when porting from C++ to C# there are a few things that change when it comes to references. So my only idea would be if you need to explicitly show that you are passing a variable by ref/const ref. Ie. in C# to pass by ref in a function call you need:
int a = 10;
foo(ref a);
So something similar to this in LUA might cause the errors you show.

God only knows what SWIG is doing. My advice is to bite the bullet and use Lua's C API, which also works with C++. It's not that hard to learn, and you'll be able to overload the foo2 method exactly the way you want. Good examples can be found in Roberto Ierusalimschy's book Programming in Lua; you can get the previous edition free online.
N.B. Since the API is C, it doesn't know from reference parameters. Your Lua userdata object should contain a pointer to the C++ object of class foo2.

Along the lines of the suggestion to use Lua's native C API, but since you're in C++, try out Luabind. It works very well once you get the hang of it. If you do try it be sure to get the latest version--it's actively maintained and getting better all the time.

If you make the lua interface with swig try this instead:
foo2(const foo* f){*this = *f;}
swig has some problems with the reference types but make the automatic conversion from pointers without problems.
I think that the const reference is the problem in swig here

You can tell SWIG how to convert the internal pointer representation to a const reference using a typemap:
%typemap(in) const Foo&
{
if(!SWIG_IsOK(SWIG_ConvertPtr(L,$argnum, (void**)$1, $1_descriptor,1)))
{
SWIG_fail;
}
}
This should generate code that looks something like this in your wrap.cpp file:
if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_Foo,1)))
{
SWIG_fail;
}
result = new Foo2(((Foo const &)*arg1);
SWIG_arg=0;
SWIG_Lua_NewPointerObj(L, result, SWIGTYPE_p_Foo2, 1); SWIG_arg++;

Related

Bad practice to call static function from external file via function pointer?

Consider the following code:
file_1.hpp:
typedef void (*func_ptr)(void);
func_ptr file1_get_function(void);
file1.cpp:
// file_1.cpp
#include "file_1.hpp"
static void some_func(void)
{
do_stuff();
}
func_ptr file1_get_function(void)
{
return some_func;
}
file2.cpp
#include "file1.hpp"
void file2_func(void)
{
func_ptr function_pointer_to_file1 = file1_get_function();
function_pointer_to_file1();
}
While I believe the above example is technically possible - to call a function with internal linkage only via a function pointer, is it bad practice to do so? Could there be some funky compiler optimizations that take place (auto inline, for instance) that would make this situation problematic?
There's no problem, this is fine. In fact , IMHO, it is a good practice which lets your function be called without polluting the space of externally visible symbols.
It would also be appropriate to use this technique in the context of a function lookup table, e.g. a calculator which passes in a string representing an operator name, and expects back a function pointer to the function for doing that operation.
The compiler/linker isn't allowed to make optimizations which break correct code and this is correct code.
Historical note: back in C89, externally visible symbols had to be unique on the first 6 characters; this was relaxed in C99 and also commonly by compiler extension.
In order for this to work, you have to expose some portion of it as external and that's the clue most compilers will need.
Is there a chance that there's a broken compiler out there that will make mincemeat of this strange practice because they didn't foresee someone doing it? I can't answer that.
I can only think of false reasons to want to do this though: Finger print hiding, which fails because you have to expose it in the function pointer decl, unless you are planning to cast your way around things, in which case the question is "how badly is this going to hurt".
The other reason would be facading callbacks - you have some super-sensitive static local function in module m and you now want to expose the functionality in another module for callback purposes, but you want to audit that so you want a facade:
static void voodoo_function() {
}
fnptr get_voodoo_function(const char* file, int line) {
// you tagged the question as C++, so C++ io it is.
std::cout << "requested voodoo function from " << file << ":" << line << "\n";
return voodoo_function;
}
...
// question tagged as c++, so I'm using c++ syntax
auto* fn = get_voodoo_function(__FILE__, __LINE__);
but that's not really helping much, you really want a wrapper around execution of the function.
At the end of the day, there is a much simpler way to expose a function pointer. Provide an accessor function.
static void voodoo_function() {}
void do_voodoo_function() {
// provide external access to voodoo
voodoo_function();
}
Because here you provide the compiler with an optimization opportunity - when you link, if you specify whole program optimization, it can detect that this is a facade that it can eliminate, because you let it worry about function pointers.
But is there a really compelling reason not just to remove the static from infront of voodoo_function other than not exposing the internal name for it? And if so, why is the internal name so precious that you would go to these lengths to hide that?
static void ban_account_if_user_is_ugly() {
...;
}
fnptr do_that_thing() {
ban_account_if_user_is_ugly();
}
vs
void do_that_thing() { // ban account if user is ugly
...
}
--- EDIT ---
Conversion. Your function pointer is int(*)(int) but your static function is unsigned int(*)(unsigned int) and you don't want to have to cast it.
Again: Just providing a facade function would solve the problem, and it will transform into a function pointer later. Converting it to a function pointer by hand can only be a stumbling block for the compiler's whole program optimization.
But if you're casting, lets consider this:
// v1
fnptr get_fn_ptr() {
// brute force cast because otherwise it's 'hassle'
return (fnptr)(static_fn);
}
int facade_fn(int i) {
auto ui = static_cast<unsigned int>(i);
auto result = static_fn(ui);
return static_cast<int>(result);
}
Ok unsigned to signed, not a big deal. And then someone comes along and changes what fnptr needs to be to void(int, float);. One of the above becomes a weird runtime crash and one becomes a compile error.

Is this C callback safe with C++ objects?

My purpose is to call some C function from my C++ code and pass some C++ objects.
In fact I am using a integration routine from the GSL libray(written in C), see this link,
My code snippet:
// main.cpp
#include <stdio.h>
#include <gsl/gsl_integration.h>
#include <myclass.h>
/* my test function. */
double testfunction ( double x , void *param ) {
myclass *bar=static_cast<myclass*>(param);
/*** do something with x and bar***/
return val;
}
int main ( int argc , char *argv[] ) {
gsl_function F; // defined in GSL: double (* function) (double x, void * params)
/* initialize.*/
gsl_integration_cquad_workspace *ws =
gsl_integration_cquad_workspace_alloc( 200 ) ;
/* Prepare test function. */
myclass foo{}; // call myclass constructor
F.function = &testfunction;
F.params = &foo;
/* Call the routine. */
gsl_integration_cquad( &F, 0.0,1.0,1.0e-10,1.0e-10,ws, &res,&abserr,&neval);
/* Free the workspace. */
gsl_integration_cquad_workspace_free( ws );
return 0;
}
In my case, direct calling gsl_integration_cquad seems OK, provided the header includes sth like "ifdef __cplusplus", my concern is about the callback F,originally defined in C, am I allowed to pass the testfunction and also the C++ foo object in this way ? .
or is there any better way to do this kind of stuff, maybe overloading and use a functor?
P.S. Am I allowed to do exeption handling within the callback function? (use try catch inside "testfunction"). It works in my case but not sure if it's legal.
I'm not familiar with the library in question, but in general,
when passing a pointer to a callback and a void* to
a C routine, which will call the callback back with the void*,
there are two things you need to do to make it safe:
The function whose address you pass must be declared extern "C".
You'll get away with not doing this with a lot of compilers, but
it isn't legal, and a good compiler will complain.
The type you convert to the void* must be exactly the same
type as the type you cast it back to in the callback. The
classic error is to pass something like new Derived to the
C function, and cast it back to Base* in the callback. The
round trip Derived*→void*→Base* is undefined
behavior. It will work some of the time, but at other times, it
may crash, or cause any number of other problems.
And as cdhowie pointed out in a comment, you don't want to
allow exceptions to propagate accross the C code. Again, it
might work. But it might not.
For the exact example you posted, the only thing you need to do
is to declare testfunction as extern "C", and you're all
right. If you later start working with polymorphic objects,
however, beware of the second point.
You can use
myclass *bar=static_cast<myclass*>(param);
with void*.
If you meant something like transporting a c++ class pointer through a c callback's void* pointer, yes it's safe to do a static_cast<>.
There's no kind of losing c++ specific attributes of this class pointer, when passed through c code. Though passing a derived class pointer, and static casting back to the base class, won't work properly as #James Kanze pointed out.
The void* will likely just be passed trough by the C library without looking at the pointed-to data, so it's not a problem if this contains a C++ class. As log as you cast the void* to the correctly there shouldn't be any problems.
To make sure the callback function itself is compatible, you can declare it as extern "C". Additionally you should make sure that no exceptions are thrown from the callback function, since the C code calling the callback won't expect those.
All together I would split up the code into one function that does the real work and another function that is used as the callback and handles the interface with the C library, for example like this:
#include <math.h>
double testfunction ( double x ,myclass *param ) {
/*** do something with x and bar***/
return val;
}
extern "C" double testfunction_callback ( double x , void *param ) {
try {
myclass *bar=reinterpret_cast<myclass*>(param);
return testfunction(x, bar);
}
catch(...) {
std::cerr << "Noooo..." << std::endl;
return NAN;
}
}

Anonymous Functions, "Parse Issue: Expected Expression"

I'm getting the titular error, but I can't for the life of me figure out how to resolve it. I've scoured the internet a fair bit, but for the most part I can't find anything that pertains directly to, or solves, the problem I'm having, and all the information I read about anonymous classes, seems to agree with the code I wrote.
The essence of what I'm trying to do is; I have a struct, and I want that struct to contain a function pointer. What I'm having trouble with is when I define an instance of the struct, I'm trying to create and pass an anonymous function to the struct. But it's giving me a compile error.
Anyways, here are the details of the actual problem, the error occurs on this line,
[&](int x) { this->moveLeft(); };
It says "Parse Issue: Expected expression" and points to the ']'
of the following code
Combatant::CharacterData Combatant::characters = {
/*Name */"SomeName",
/*Folder */"SomeFolder",
/*Offense */1.0f,
/*Defense */1.0f,
/*Combos */{
{KeyMemory(KeyMemory::MOVE_LEFT, KeyMemory::JUMP),
[&](int x) { this->moveLeft(); };
},
{KeyMemory(KeyMemory::MOVE_LEFT, KeyMemory::JUMP),
[&](int x) { this->moveLeft(); };
}
}
}
The CharacterData struct is defined by this code:
struct Combo {
KeyMemory controls;
void (*execute)(int);
};
struct CharacterData {
std::string name;
std::string folder;
float offense;
float defense;
Combo comboList[5];
};
Any help, would be much appreciated. ^_^
You might need to use a std::function<void(int)> to hold your lambda. (Particularly since you are using [&]).
Also, I'm not sure [&] actually makes sense in a global context. Maybe you should be passing in the object to call moveLeft on, and using []. Also, that change might let you use your simple function pointer instead of a std::function.
The problem turned out to be that Clang, which is the compiler used by Xcode/Apple doesn't yet support lambda functions. From what I read however the feature is coming in the future.

Possible to have C++ anonymous functions with boost?

I'm trying to solve a problem that anonymous functions make much, much easier, and was wondering if this was possible in c++.
What I would like to do is (essentially)
template<typename T>
T DoSomething(T one, function<T(T)> dosomething)
{
return one + dosomething(5);
}
void GetMyVal(...)
{
DoSomething<int>(1, /*anonymous func here*/)
}
This example is very, very simplified for what I have to do. In C# I would do p => p*5. I know this is easy with C++0x, but I can't use that. I feel that I should be able to do it with either boost::lambda, or a compination of boost::bind and boost::function with placeholders, but I can't seem to get it to work. This may not be possible and thats also fine, but please answer if its not possible. Thanks.
EDIT:
Ok, it seems the simple case of an int works fine, what about a more complicated structure? So, lets try
struct NumHolder
{
int x;
}
template<typename T>
T DoSomething(T one, function<T(NumHolder)> dosomething)
{
NumHolder temp;
temp = 5
return one + dosomething(temp);
}
void GetMyVal(...)
{
DoSomething<int>(1, /*anonymous func here*/)
}
Here my C# expression would be along the lines of p => p.temp * 5. Is this possible to do in C++ with boost?
EDIT 2: OK, now I'm just curious :D How would I call a function within the lambda expression? So, if we have
int ChangeVal(int mult)
{
return mult*5;
}
struct NumHolder
{
int x;
}
template<typename T>
T DoSomething(T one, function<T(NumHolder)> dosomething)
{
NumHolder temp;
temp = 5
return one + dosomething(temp);
}
void GetMyVal(...)
{
DoSomething<int>(1, /*anonymous func here*/)
}
In C# I could call p => ChangeVal(p). What would the syntax be for this with the C++ lambda expressions?
As Anders notes in his answer, boost::lambda can be useful, but the code can become hard to read in some cases. It thus depends on what you want to do in your anonymous function.
For simple case like the p => p * 5 you mention in your question, it seems to me that using Lambda or Bind would be reasonable, though:
DoSomething(1, _1 * 5);
Edit:
Your second example hits one area where the syntax gets quickly verbose: Member (data or function) access. Because the "dot" operator can't be overloaded in C++, you have to use a bind expression to get the "x" from the argument:
DoSomething(1, bind(&NumHolder::x, _1) * 5);
or, with Boost.Lambda, use the overloaded ->* operator:
DoSomething(1, &_1->* &NumHolder::x * 5);
Edit 2:
OK, one last time :)
In your last question, you write that in C#, you'd write p => ChangeVal(p), but the code above shows a ChangeVal taking an int, not a NumHolder, so it's not clear what you mean.
Assuming that ChangeVal takes an int and that you want the anonymous function to do the equivalent of ChangeVal(the_arg.x), you'd write this with Boost.Lambda:
DoSomething(1, bind(&ChangeVal, &_1->*&NumHolder::x));
or this with Boost.Bind (works with Lambda too):
DoSomething(1, bind(&ChangeVal, bind(&NumHolder::x, _1));
No, it isn't possible to do in a simple way. boost::lambda can help, but in my opinion the code is so hard to read when using it so I would avoid it.
I think the equivalent to C# p=>p*5 would be _1*5, but I've only looked at it briefly so I'm not sure. For simple stuff it works, but as soon as you need control structures you will have to use another set of control structures which are functionally based, rather than imperative. I found this so different from normal C++ code that I decided for myself that it is not worth using it, because it makes the code so hard to read for others.
boost doesn't extend syntax of c++. there are no anonymous functions in c++.

Initializing and assigning values,from pass by reference

Okay, this is just a minor caveat. I am currently working with the lovely ArcSDK from ESRI. Now to get a value from any of their functions, you basically have to pass the variable, you want to assign the value to.
E.g.:
long output_width;
IRasterProps->get_Width(&output_width);
Its such a minor thing, but when you have to pick out around 30 different pieces of data from their miscellaneous functions, it really starts to get annoying.
So what i was wondering is it possible to somehow by the magic of STL or C++ change this into:
long output_width = IRasterProps->get_Width(<something magical>);
All of the functions return void, otherwise the off chance some of them might return a HRESULT, which i can safely ignore. Any ideas?
***EDIT****
Heres the final result i got which works :)!!!!!
A magic(P p, R (__stdcall T::*f)(A *)) {
A a;
((*p).*f)(&a);
return a;
}
I know I've already answered, but here's another way. It's better in that it's faster (no boost::function overhead) and avoids the binders (since people seem to have an aversion to them), but is worse in that it's much less general (since it only works for one-argument member functions).
template <typename P, typename T, typename A>
A magic(P p, void (T::*f)(A &)) {
A a;
((*p).*f)(a);
return a;
}
Which you'd call like this:
long output_width = magic(raster_props_object, &IRasterProps::get_Width);
Or, if you happen to be using GCC, we can use some more tricks:
#define MORE_MAGIC(p,f) ({ \
typedef __typeof(*(p)) big_ugly_identifier; \
magic((p),(&big_ugly_identifier::f)); \
})
Which will let us do this:
long output_width = MORE_MAGIC(raster_props_object, get_Width);
(Bonus points if the naming conventions made you think of a PDP-10.)
EDIT: Updated to take any pointer-like type, so it will now work with shared_ptr, iterators, and hopefully _com_ptr.
EDIT: Oops, they're pointers, not references. Here's a version (or overload) that deals with that, and allows -- by ignoring -- arbitrarily-typed return values.
template <typename P, typename T, typename A, typename R>
A magic(P p, R (T::*f)(A *)) {
A a;
((*p).*f)(&a);
return a;
}
This is not quite what you specified because you need to wrap get() around the method, but it works:
template<class T, class S>
T get(S fun(T&)) {
T result;
fun(result);
return result;
}
void foo(int& x) {
x = 5;
}
bool bar(char& x) {
x = 'c';
return false;
}
int main() {
int x = get(foo);
char y = get(bar);
return 0;
}
Can you derive from IRasterProps? Being that the case you can construct your own interface to it.
EDIT: Following on the concept you can probably also apply the Adapter design pattern (or even a Facade if you wish to apply a common interface to several like-minded classes of the SDK).
Looks like a COM object to me.
Visual C++ supports an #import directive to import the type library, and create high-legel wrappers. So you either end up with
width = ptr->GetWidth();
or - even better -
width = ptr->Width;
If a function fails, the HRESULT returned will be transformed into an _com_error exception.
I've used that successfully on many OS and 3rd party COM objects, makes them much easier to use.
Note that you control the wrapper generation through options, the first thing I do is usually adding a rename_namespace or no_namespace, because otherwise the symbold end up in a namespace depending on the typelib name, which is usually ugly.
also, unless you use named_guids option, you might needto change CLSID_xxx and IID_xxx constants to __uuidof(xxx).
EDIT: In retrospect, I'm not sure this one will actually work, since I don't think the template arguments will deduce. Buyer Beware.
Sure! What you need is something to which you can pass a function that will call it and return you the outputted value.
Here's the easy, if less efficient way:
template <typename T>
T magic(boost::function<void(T&)> f) {
T x;
f(x);
return x;
}
Which you'd then call like this using boost::lambda:
long output_width = magic(raster_props_object->*&IRasterProps::get_Width);
Or like this, using boost::bind:
long output_width = magic(bind(&IRasterProps::get_Width, raster_props_object, _1));
You can get rid of boost::function, but that's uglier. Probably worth it, though.
Don't think this is possible. Assigning void to a long should be an error in any case.
Remember, it's probably more performant to pass-by-reference than to return a large object. (won't really make a difference with long's though)
Compiling this:
void foo(long &a) {
}
int main(void) {
long a=0;
a = foo(a);
return 0;
}
gives this error:
g++ x.cc
x.cc: In function ‘int main()’:
x.cc:9: error: void value not ignored as it ought to be
I'm not aware of something insane you could do, precisely like you're asking, and if there was some insane hackery that did work on some peculiar platform I'm pretty sure in a code-review I'd hate it.
It may may more sense to either...
define some trivial inline function wrappers around the APIs you care about
make a specialized class descend from IRasterProps (or whatever) that provides the appropriate accessor methods.
Either of those will impact maintenance time of the code but would safely and cleanly give you the call syntax you are looking for.