Is there a way to have a function that executes a different function but carries out the same steps independent of the function?
This example would better portray what I mean:
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
if (!SQL_SUCCEEDED(ret)) {
printf("SQL Failed\n");
DisplayError(SQL_HANDLE_STMT, stmt);
}
ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
if (!SQL_SUCCEEDED(ret)) {
printf("SQL Failed\n");
DisplayError(SQL_HANDLE_STMT, stmt);
}
I can't think of a more general example other than my specific needs, but the common part here is that I am always checking if the return variable from an SQL function is an error, and then if it is, printing said error. I feel this would be better if it was possible to wrap the error checking in a debug mode, and strip it off in a release mode, but I don't know how to do it. I am hoping that there is an answer along the lines of
SQL(ret, SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env));
Where wrapping the entire call in a defined SQL function would call any sql function passed in, as well as assigning it to the variable so long as the return types are the same.
I have tried to come up with something such as
#define SQL(a, x) (a = x; if (!SQL_SUCCEEDED(a)) { printf("SQL Failed\n"); DisplayError(SQL_HANDLE_STMT, stmt);})
but this doesn't work.
You can pass functions by copying or by const reference...
int MyFunction( const std::function<int(void)> & fn )
{
return fn();
}
int MyFunction2( std::function<int(int)> fn )
{
return fn(7);
}
and either pass a Lambda
MyFunction([]{ return SomeIntFunction(); });
or a reference to a static function
MyFunction(&StaticIntFunction);
or bind the function
MyFunction(std::bind(&Class::SomeIntFunction, classInstance));
Related
I'm using glad to generate OpenGL bindings, and have generated a debug build which includes the following:
// this symbol only exists if generated with the c-debug generator
#define GLAD_DEBUG
typedef void (* GLADcallback)(const char *name, void *funcptr, int len_args, ...);
/*
* Sets a callback which will be called before every function call
* to a function loaded by glad.
*
*/
GLAPI void glad_set_pre_callback(GLADcallback cb);
/*
* Sets a callback which will be called after every function call
* to a function loaded by glad.
*
*/
GLAPI void glad_set_post_callback(GLADcallback cb);
The documentation gave an example how to define this callback, which looks like this:
void _post_call_callback_default(const char *name, void *funcptr, int len_args, ...) {
GLenum error_code;
error_code = glad_glGetError();
if (error_code != GL_NO_ERROR) {
fprintf(stderr, "ERROR %d in %s\n", error_code, name);
}
}
What I don't understand is how I'm supposed to access the varargs. I'm guessing that they are the values that are passed to the OpenGL function, and thus can be any type. However, I must specify the type to va_arg in order to access the values.
I feel that the parameter len_args is hinting that there is some way to iterate over the varargs, but I don't understand how it's supposed to be used without knowing the types. How are they meant to be used?
You have the source code of glad.c whenever the glad_set_post_callback function is called. There you can see that the parameters depends on which function was called. So I think you need to check the name/funcptr parameter.
For example if glEnable was called then you have:
void APIENTRY glad_debug_impl_glEnable(GLenum arg0) {
_pre_call_callback("glEnable", (void*)glEnable, 1, arg0);
glad_glEnable(arg0);
_post_call_callback("glEnable", (void*)glEnable, 1, arg0);
}
which means that the first parameter is a GLenum. See this question an-example-of-use-of-varargs-in-c on how to use variable arguments:
It would be something like this (not tested):
void _post_call_callback_default(const char *name, void *funcptr, int len_args, ...) {
GLenum error_code;
error_code = glad_glGetError();
if (error_code != GL_NO_ERROR && funcptr == (void*)glEnable /* or strcmp(name,"glError") == 0*/) {
va_list ap;
va_start(ap, len_args);
GLenum arg0 = va_arg(ap, GLenum);
va_end(ap);
printf("Called glError(%d) with Error %d\n", arg0, error_code);
}
}
You can so decide for which functions you want a better debug log. I am not aware if there is already some free code that gives a better debug output.
Maybe it's better to compare funcptr with the pointer to glEnable instead of comparing the string name with "glError". I didn't tested it. The code above is just an example, I would write it differently.
I am writing a series of mock functions in C using CMocka
Some of these take pointers as input variables and I am not sure whether I should check them (ptr != NULL) or not.
In general, is the mock function responsible to perform input checking?
If yes, how should it behave when an error is found?
Should it use the assert functions provided by the framework?
If your mentioned pointers are parameters which are passed to some mocked functions you can check them with check_expected(...) and expect_value().
void function_under_test(){
char c = 'c';
int ret;
//...
ret = subfunction(&c);
if(ret == 0)
printf("Success");
//...
}
int __wrap_mocked_subfunction(int* p_paramater){
check_expected(p_paramater);
return mock();
}
test(void **state){
expect_not_value(__wrap_mocked_functions, p_paramater, NULL);
will_return(0);
function_under_test();
}
Errors are then reported automatically.
An example can be found here: https://lwn.net/Articles/558106/
If you really need to check them depends on you and your code and your opinion and your requirements.
Let us assume I always need the direkt return type of the function to be of a errorcode (success of calculation or failure) , then I will return some arguments as parameters. Is it better to define them as reference (and create them before empty) or better to return pointer?
Edit: I should be more precise: The errorcode is obligatory because I have to stick to the coding guidline given.
Possibility A:
ErrorCode func( some_parameters ... , ReturnType & result)
...
ReturnType result; // empty constructor, probably not good practice
func( some_parameters ..., result)
Possibility B:
ErrorCode func( some_parameters ... , ReturnType * result){
...
result = new ReturnType(...)
...
}
...
ReturnType * result; // void pointer
func( some_parameters ..., result)
...
delete result; // this is needed if I do not use a smart pointer
Even better: Maybe you have a more appropriate solution?
Edit: Please indicate which standard you are using, since unfortunatelly (guidelines) I have to stick to C++98.
I would do the following (and in general do)
1.) throw an exception instead of returning error codes
if this is not possible (for any reason)
2.) return the pointer directly (either raw or std::unique_ptr) and return nullptr for failure
if return type has to be bool or not all objects returned are (pointers / heap allocated)
3.) return your error code (bool or enum class) and accept a reference parameter for all objects that are to be initialized (must have objects so to speak) and pointers to objects that may be optionally created / initialized
if the object cannot be created in advance to the call (e.g. because it is not default constructible)
4.) pass a reference to a pointer (raw or std::unique_ptr) or a pointer to a pointer, which will then be filled by the function
std::optional (or similar) may be an option if you only have a true/false return code.
I don't like returning std::pair or std::tuple because it can make your code look quite annoying if you have to start using .first/.second or std::get<>() to access your different return types. Using std::tie() can reduce this a little bit, but it is not (yet) very comfortable to use and prevents the use of const.
Examples:
std::unique_ptr<MyClass> func1() { /* ... */ throw MyException("..."); }
std::unique_ptr<MyClass> func2() { /* ... */ }
ErrorCode func3(MyClass& obj, std::string* info = nullptr) { /* ... */ }
ErrorCode func4(std::unique_ptr<MyClass>& obj) { /* ... */ }
int main()
{
try
{
auto myObj1 = func1();
// use ...
}
catch(const MyException& e)
{
// handle error ...
}
if(auto myObj2 = func2())
{
// use ...
}
MyClass myObj3;
std::string info;
ErrorCode error = func3(myObj3, &info);
if(error == ErrorCode::NoError)
{
// use ...
}
std::unique_ptr<MyClass> myObj4;
ErrorCode error = func4(myObj4);
if(error == ErrorCode::NoError)
{
// use ...
}
}
Edit: And in general it is advisable to keep your API consistent, so if you already have a medium or large codebase, which makes use of one or the other strategy you should stick to that (if you do not have good reasons not to).
This is a typical example for std::optional. Sadly it isn't available yet, so you want to use boost::optional.
This is assuming that the result is always either "success with result" or "fail without result". If your result code is more complicated you can return
std::pair<ResultCode, std::optional<ReturnType>>.
It would be good style to to use the return value for all return information. For example:
std::tuple<bool, ReturnType> func(input_args....)
Alternatively, the return type could be std::optional (or its precursor) if the status code is boolean, with an empty optional indicating that the function failed.
However, if the calculation is supposed to normally succeed, and only fail in rare circumstances, it would be better style to just return ReturnType, and throw an exception to indicate failure.
Code is much easier to read when it doesn't have error-checking on every single return value; but to be robust code those errors do need to be checked somewhere or other. Exceptions let you handle a range of exceptional conditions in a single place.
Don't know if it's applicable in your situation but if you have only two state return type then maybe just return pointer from your function and then test if it is nullptr?
I have a class called Entity, which has many functions like onPickup, onDrop, onUse etc. What I want to do is, write a script that defines all of these functions and make them callable from the C++ functions. So the functions defined in C++ would just be calling their corresponding Lua functions that have some functionality.
But here's the problem, I want every script that I write, for every Entity in the program to be working in it's own scope.
I'm using LuaBind, and I have no prior experience with Lua, so I'm a little lost here.
I don't use lua bind but this may help. The idea is to register the lua functions in your C++ class and keep a reference to the lua function in your C++ class.
To define a lua function that is callable from C/C++ I use luaL_ref to store a reference to the callback function in my C++ object.
// a little helper function
template <typename T>
T *Lua_getUserData(lua_State *L) {
assert(lua_isuserdata(L, 1) == 1);
T **v = (T **) lua_touserdata(L, 1);
assert(v != NULL);
return *v;
}
int lua_FormRegisterMethods(lua_State *L) {
Entity *f = Lua_getUserData<Entity>(L);
assert(lua_istable(L, 2) == 1); // check the next parameter is a table
lua_pushvalue(L,2); // dup the table
f->LuaTable = luaL_ref(L, LUA_REGISTRYINDEX); // keep a reference to the table
lua_getmetatable(L, 2); // get the metatable
lua_pushstring(L, "OnClick");
lua_rawget(L, -2); // get the OnClick Lua Function
f->LuaMethod = luaL_ref(L, LUA_REGISTRYINDEX); // save a reference to it
return 0;
}
and then you can get the lua method in your C++ event
lua_rawgeti( LuaInstance->L, LUA_REGISTRYINDEX, LuaMethod );
assert(lua_isfunction(LuaInstance->L, -1) == 1);
now you can call this function with self set to the table you saved earlier. hth
You can call a Lua function with, e.g.
int callLuaFunction(lua_State* lua_state) {
return luabind::call_function<int>(lua_state, "myluafunction", param1);
}
if the Lua function returns an int and takes 1 parameter.
I'm pretty sure you can make as many lua_State's as you want. Just pass the correct one for the entity into call_function.
To fully implement this the way you will probably want to will require digging around a bit in some of the more esoteric bits of Lua. It is well worth the time though. I'll show a very trimmed down version of how I have handled this. Be warned, there are a lot of little bits all working together here - mainly saving and calling saved functions and using c++ objects as Lua user data.
First we need a c++ class which will store events handlers (lua functions) as lua references which are simple ints. I am using an array here but you could use whatever makes sense. The main thing happening here is that you want to be able to call a lua function which is referred to by the int reference.
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <string>
#include <iostream>
#include <assert.h>
using namespace std;
enum enum_event_types {
ON_USE, ON_DROP, ON_WHATEVER, EVENT_COUNT
};
class Entity {
private:
int events[EVENT_COUNT];
public:
lua_State* lua;
void setEventHandler(int event, int ref) {
assert(event < EVENT_COUNT);
events[event] = ref;
}
void callEventHandler(int event) {
int error;
assert(event < EVENT_COUNT);
// to call the function we need to get it from the registry index
lua_rawgeti(lua, LUA_REGISTRYINDEX, events[event]);
error = lua_pcall(lua, 0, 0, 0); // use protected call for errors
if (error) {
printf("error: %s", lua_tostring(lua, -1));
lua_pop(lua, 1);
}
}
};
Now you want to expose your Entity class to Lua. If you are not familiar with how this is done there is a good article here. Essentially what is going on is that we are setting the user data returned from Entity.new() to a pointer to a pointer. This is so Lua does not garbage collect your object. Then create a meta table for "Entity" which will
hold all of the methods exposed to Lua.
int L_newEntity(lua_State* L) {
Entity **e = (Entity **)lua_newuserdata(L, sizeof(Entity *));
*e = new Entity();
(*e)->lua = L;
lua_getglobal(L, "Entity");
lua_setmetatable(L, -2);
return 1;
}
int L_setOnUse(lua_State* L) {
Entity** e = (Entity**) lua_touserdata(L, 1);
lua_pushvalue(L, 2);
int ref = luaL_ref(L, LUA_REGISTRYINDEX);
(*e)->setEventHandler(ON_USE, ref);
return 0;
}
// this will be exposed to Lua as a table called Entity
static const luaL_Reg L_entityMethods[] = {
{"new", L_newEntity},{"setOnUse", L_setOnUse},{NULL, NULL}
};
Now set up the Lua state and create the Entity table and create a test. The test will create an Entity and set its event handler to a Lua function passed to it. Finally test that the Lua function is being called by the c++ object.
int main() {
Entity** e;
int error;
lua_State* L=lua_open();
luaL_openlibs(L);
luaL_register(L, "Entity", L_entityMethods);
lua_pushvalue(L,-1);
lua_setfield(L, -2, "__index");
lua_pop(L, 1);
luaL_loadstring(L,
"e = Entity.new(); "
"e:setOnUse(function()"
" print('Some of them want to use you')"
"end);");
error = lua_pcall(L, 0, 0, 0);
if (error) {
printf("error: %s", lua_tostring(L, -1));
lua_pop(L, 1); /* errors must be popped from stack */
}
lua_getglobal(L, "e");
if (lua_isuserdata(L, 1)) {
e = (Entity**) lua_touserdata(L, 1);
(*e)->callEventHandler(ON_USE);
}
return 0;
}
This is far from complete. First of all if you ever need to set an event handler twice you will need to use luaL_unref to clear out the old reference first. Second you will probably want to pass some data about the event which occurred to the event handler. The current event handler does not take any data so gives the user of the api very little to go on. It should probably at least pass a reference to the object which is calling the event. This can be used to create very powerful and usable Apis in Lua. Good luck!
What is a good way to return success or one or more error codes from a C++ function?
I have this member function called save(), which saves to each of the member variables, there are at least ten of these member variables that are saved-to, for the call to save(), I want to find out if the call failed, and if so, on which member variable (some are hard failures, some are soft).
You can either return an object that has multiple error fields or you can use 'out'parameters.
How you do this depends on your design and what exactly you are trying to return back. A common scenario is when you need to report back a status code along with a message of sorts. This is sometimes done where the function returns the status code as the return value and then returns the message status via an 'out' parameter.
If you are simply returning a set of 'codes', it might make more sense to construct a struct type and return that. In that case, I would be prone to pass it in as an out parameter and have the method internally update it instead of allocating a new one each time.
Are you planning on doing this once or many times?
I know this doesn't really answer your question, but...
In C++ you should use exceptions instead of returning error codes. Error codes are most commonly used by libraries which don't want to force the library user to use a particular error handling convention, but in C++, we already have stdexcept. Of course, there might be reasons you don't use exceptions, such as if you're writing embedded code or kernel extensions.
I usually use a boost::tuple:
typedef boost::tuple<int,int> return_value;
return_value r = my_function();
int first_value = boost::get<0>( r );
int second_valud = boost::get<1>( r );
EDIT
You can also use boost::tie to extract the values from a tuple:
boost::tie( first_value, second_value ) = r;
The simplest way to return two values is with the std::pair<> template:
I would use a bitset if you're intention is to purely return error states. e.g.
const bitset<10> a_not_set(1);
const bitset<10> b_not_set(2);
const bitset<10> c_not_set(4);
...
bitset<10> foo(T& a, T& b, T& c, ...)
{
bitset<10> error_code = 0;
...
if ( /* a can't be set */ )
{
error_code |= a_not_set;
}
...
if ( /* b can't be set */ )
{
error_code |= b_not_set;
}
...
// etc etc
return error_code;
}
bitset<10> err = foo(a, b, c, ... );
if (err && a_not_set)
{
// Blah.
}
You need to return them as output parameters:
bool function(int& error1, int& error2, stringx& errorText, int& error3);
You can use an integer with bit manipulation (aka flags).
I probably try to throw an exception first but it depends on your coding paradigm. Please check some books or articles about reasons why c++ exception handling might be better.
If I really need to stick to retrun-error-code style, I would define a eunm type for specifying errors with bit operations..
enum error
{
NO_ERROR = 0,
MEMBER_0_NOT_SAVED = 1,
MEMBER_1_NOT_SAVED = 1 << 1,
MEMBER_2_NOT_SAVED = 1 << 2,
// etc..
};
int save()
{
int ret = NO_ERROR;
// fail to save member_0
ret |= MEMBER_0_NOT_SAVED;
// fail to save member_1
ret |= MEMBER_1_NOT_SAVED;
// ....
return ret;
}
int main(void)
{
int ret = save();
if( ret == NO_ERROR)
{
// good.
}
else
{
if(ret & MEMBER_0_NOT_SAVED)
{
// do something
}
if(ret & MEMBER_1_NOT_SAVED)
{
// do something
}
// check the other errors...
}
}
This is just a rough example. It's better to put this into a class or use a namespace.
I am not familiar with the internals and constrains of your project, but if possible, try to use exceptions instead of error codes.
The reasons are listed here, at C++ FAQ lite, and they conclude with:
So compared to error reporting via return-codes and if, using try / catch / throw is likely to result in code that has fewer bugs, is less expensive to develop, and has faster time-to-market.