Why isn't the following valid?
bool trigger(t_evt evt) const {
std::shared_ptr<I> ptr = this->instance.lock();
if (!ptr) {
return false;
}
(ptr->*f)(evt); // -> causes a compilation error
return true;
}
The error in english is something like that (I don't get it in english):
'->*' : improper usage, left operand of type 'std::shared_ptr<ListenerCardsChange>'
f is a pointer to a member function.
Note that (*ptr.*f)(evt); works fine.
That's because shared_ptr<T>, and also unique_ptr<T, D>, do not overload operator->*. That's arguably a defect, but I haven't thought about it much and am not 100% sure that there isn't some reason for that.
Use the (*ptr.*f)(evt) syntax.
Related
We use a third party Tcl parsing library to validation Tcl script for both syntax and semantic checking. The driver was written in C and defined a set of utility functions. Then it calls Tcl_CreateObjCommand so the script could call these C functions. Now we are in the process of porting the main program to go and I could not find a way to do this. Anyone know a way to call golang functions from Tcl script?
static int
create_utility_tcl_cmds(Tcl_Interp* interp)
{
if (Tcl_CreateObjCommand(interp, "ip_v4_address",
ip_address, (ClientData)AF_INET, NULL) == NULL) {
TCL_CHECKER_TCL_CMD_EVENT(0, "ip_v4_address");
return -1;
}
.....
return 0;
}
Assuming you've set the relevant functions as exported and built the Go parts of your project as in
Using Go code in an existing C project
[…]
The important things to note are:
The package needs to be called main
You need to have a main function, although it can be empty.
You need to import the package C
You need special //export comments to mark the functions you want callable from C.
I can compile it as a C callable static library with the following command:
go build -buildmode=c-archive foo.go
Then the core of what remains to be done is to write the C glue function from Tcl's API to your Go code. That will involve a function something like:
static int ip_address_glue(
ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) {
// Need an explicit cast; ClientData is really void*
GoInt address_family = (GoInt) clientData;
// Check for the right number of arguments
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "address");
return TCL_ERROR;
}
// Convert the argument to a Go string
GoString address;
int len;
address.p = Tcl_GetStringFromObj(objv[1], &len);
address.n = len; // This bit is hiding a type mismatch
// Do the call; I assume your Go function is called ip_address
ip_address(address_family, address);
// Assume the Go code doesn't fail, so no need to map the failure back to Tcl
return TCL_OK;
}
(Credit to https://medium.com/learning-the-go-programming-language/calling-go-functions-from-other-languages-4c7d8bcc69bf for providing enough information for me to work out some of the type bindings.)
That's then the function that you register with Tcl as the callback.
Tcl_CreateObjCommand(interp, "ip_v4_address", ip_address_glue, (ClientData)AF_INET, NULL);
Theoretically, a command registration can fail. Practically, that only happens when the Tcl interpreter (or a few critical namespaces within it) is being deleted.
Mapping a failure into Tcl is going to be easiest if it is encoded at the Go level as an enumeration. Probably easiest to represent success as zero. With that, you'd then do:
GoInt failure_code = ip_address(address_family, address);
switch (failure_code) {
case 0: // Success
return TCL_OK;
case 1: // First type of failure
Tcl_SetResult(interp, "failure of type #1", TCL_STATIC);
return TCL_ERROR;
// ... etc for each expected case ...
default: // Should be unreachable, yes?
Tcl_SetObjResult(interp, Tcl_ObjPrintf("unexpected failure: %d", failure_code));
return TCL_ERROR;
}
Passing back more complex return types with tuples of values (especially a combination of a success indicator and a “real” result value) should also be possible, but I've not got a Go development environment in order to probe how they're mapped at the C level.
Was told today that this was a "clever way of making something like a constructor" but it "sews the seeds of destruction" even though it works. I've been searching and I can't seem to figure out why. Thanks.
Person* makePerson(std::string name, std::int num) {
Person p(name, num);
return &p;
}
You are returning a pointer to a variable whose lifetime is over when the function returns. This is useless and will lead to undefined behavior.
You want something like this:
std::unique_ptr<Person> makePerson(std::string name, std::int num) {
std::unique_ptr<Person> p(new Person(name, num));
return std::move(p);
}
P.S.: Use int not std::int.
(this is a contrived example)
I want to compute std::is_any of empty() on a std::vector<std::vector>.
I can do it with lambda expressions:
std::any_of(vecs.begin(), vecs.end(),
[](std::vector<T> const &v) { return v.empty(); });
that lambda looks needlessly ugly to me. Is there a way to use std::bind in this situation instead?
I know you asked for std::bind, but you can do the same thing with std::mem_fn with very little hassle:
std::any_of(begin(vecs), end(vecs), std::mem_fn(&std::vector<T>::empty));
(still not as clean as the lambda though, in my opinion.)
Challenge accepted:
std::any_of(vecs.begin(), vecs.end(),
std::bind(&std::vector<T>::empty, std::placeholders::_1));
The following uses std::mem_fn instead of std::bind, tested with GCC-4.9:
std::any_of(vecs.begin(), vecs.end(), std::mem_fn(&std::vector<T>::empty));
I suggest that this could be enough but would we use uglier syntax anyway
bool is_empt(vector<int>& p){
return p.empty();
}
int main (){
// placeholders and bind function TRY
vector<vector<int>> v ;
v.resize(5);
auto fn = std::bind(is_empt , placeholders::_1);
if (std::any_of(all(v) , [fn] (std::vector<int> &v1) {return fn(v1);}))
cout << "True\n";
return 0;
}
Okay, I believe in defensive programming. I assume that if I get a pointer it might be null (especially when using GSOAP). Therefore before I try to use the value of the pointer, I always check to make sure the pointer is not null.
In my current code, this is leading to a lot of nearly identical statements.
if (res->A) {
item.out_trace->a = *res->A;
}
if (res->B) {
item.out_trace->b = *res->B;
}
if (res->C) {
item.out_trace->b = *res->C;
}
I realize that I could always go and define a macro for this, but I am wondering if there is a neat C++11 trick to do that. I would love something like the C# ??
// Set y to the value of x if x is NOT null; otherwise,
// if x = null, set y to -1.
int y = x ?? -1;
Thanks.
Perhaps a template like this would meet your need:
template<typename T>
T safe_get( T const *ptr, T defval = T{} ) {
return ptr ? *ptr : std::move(defval);
}
It could be used like this:
item.out_trace->a = safe_get( rez->A );
Ideally it would be inlined and effectively zero-overhead (other than the inherent overhead of doing the safety check and having a branch, of course).
I need some advice on "forwarding" arguments to a callee (in the LLVM-IR).
Suppose I have a function F that is called at the beginning of all other functions in the module. From F I need to access (read) the arguments passed to its immediate caller.
Right now to do this I box all arguments in the caller inside a struct and pass a i8* pointer to the struct to F, alongside an identifier telling which caller F is being called from. F has then a giant switch that branches to the appropriate unboxing code. This must be done because the functions in the module have differing signatures (differing argument/return value count and types; even differing calling conventions), but it is obviously suboptimal (both from a performance and code size point-of-view) because I need to allocate the struct on the stack, copy the arguments inside of it, passing an additional pointer to F and then performing the unboxing.
I was wondering if there's a better way to do this, i.e. a way to access from a function the stack frame of its immediate caller (knowing, thanks to the identifier, which caller the function was called from) or, more in general, arbitrary values defined in its immediate caller. Any suggestions?
note: the whole point of what I'm working on is having a single function F that does all this; splitting/inlining/specializing/templating F is not an option.
to clarify, suppose we have the following functions FuncA and FuncB (note: what follows is just pseudo-C-code, always remember we are talking about LLVM-IR!)
Type1 FuncA(Type2 ArgA1) {
F();
// ...
}
Type3 FuncB(Type4 ArgB1, Type5 ArgB2, Type6 ArgB3) {
F();
// ...
}
what I need is an efficient way for the function F to do the following:
void F() {
switch (caller) {
case FuncA:
// do something with ArgA1
break;
case FuncB:
// do something with ArgB1, ArgB2, ArgB3
break;
}
}
as I explained in the first part, right now my F looks like this:
struct Args_FuncA { Type2 ArgA1 };
struct Args_FuncB { Type4 ArgB1, Type5 ArgB2, Type6 ArgB3 };
void F(int callerID, void *args) {
switch (callerID) {
case ID_FuncA:
Args_FuncA *ArgsFuncA = (Args_FuncA*)args;
Type2 ArgA1 = ArgsFuncA->ArgA1;
// do something with ArgA1
break;
case ID_FuncB:
Args_FuncB *ArgsFuncB = (Args_FuncB*)args;
Type4 ArgB1 = ArgsFuncB->ArgB1;
Type5 ArgB2 = ArgsFuncB->ArgB2;
Type6 ArgB3 = ArgsFuncB->ArgB3;
// do something with ArgB1, ArgB2, ArgB3
break;
}
}
and the two functions become:
Type1 FuncA(Type2 ArgA1) {
Args_FuncA args = { ArgA1 };
F(ID_FuncA, (void*)&args);
// ...
}
Type3 FuncB(Type4 ArgB1, Type5 ArgB2, Type6 ArgB3) {
Args_FuncB args = { ArgB1, ArgB2, ArgB3 };
F(ID_FuncB, (void*)&args);
// ...
}
IMHO you've done it right. While there are solutions in machinecode assembly, I am afraid there might be no solution in LLVM assembly, as it's "higher level". If you'd like to run a function on the beginning of some functions have you thought about checking
debugger sources (like gdb)
Binary Instrumentation with Valgrind
I know it's not direct answer, but I hope it might be helpful in some way ;).
Not sure if this helps, but I had a similar problem and got around the limitations of LLVM's tbaa analysis by using a llvm vector to store the intermediate values. LLVM optimization passes were later able to optimize the vector load / stores into scalar registers.
There were a few caveats as I recall. Let me know if you explore this route and I can dig up some code.