cannot use p (variable of type _Ctype_ulong) as "sdk/http/context"._Ctype_ulong value in assignment - cgo

How can i pass cgo pointer across different pkg, I want to share the context in my cgo project.
pointer.go
package context
import "C"
var Ptr C.ulong
main.go
package main
import (
"sdk/engine/app"
"sdk/http/context"
)
// #include "../../lib/libsdk.h"
// #cgo LDFLAGS:-L../../lib/ -lsdk
import "C"
var appName = "sdk"
func main() {
app := NewApp(appName)
p := C.initSDK(C.CString(config.ConfigFileUsed()))
context.Ptr = p
//---<- the error is there.
app.Startup()
}

Related

Replacement + Side effect

While visiting a compilation unit--- and given a certain condition- I would like to apply a transformation (using the => operator) and count the number of times the same transformation was applied for a given compilation unit.
I was able to perform that using a kind of "global module variable", but I am quite sure that it is possible to combine both replacements and actions within a single visit expression. Is that possible?
module MultiCatch
import lang::java::\syntax::Java18;
import ParseTree;
import IO;
import Map;
import Type;
import List;
// sure, I don't like global variables.
//
// However I could not find a way to perform both
// a replacement and count the number of times
// it was applied in the same compilation unit.
int numberOfOccurences = 0;
/**
* Refactor a try-catch statement to use the
* MultiCatch construct of Java 7.
*/
public tuple[int, CompilationUnit] refactorMultiCatch(CompilationUnit unit) {
numberOfOccurences = 0;
CompilationUnit cu = visit(unit) {
case (TryStatement)`try <Block b1> <Catches c1>` => (TryStatement)`try <Block b1> <Catches mc>`
when mc := computeMultiCatches(c1)
};
return <numberOfOccurences, cu>;
}
/*
* Based on a simple notion of similarity,
* this function calculates the possible
* occurences of MultiCatch.
*/
private Catches computeMultiCatches(cs){
map [Block, tuple[list[CatchType], VariableDeclaratorId, Block] ] mCatches =();
visit(cs){
case(CatchClause)`catch (<CatchType t> <VariableDeclaratorId vId>) <Block b>` :{
if (b in mCatches){
<ts, vId, blk> = mCatches[b];
ts += t;
mCatches[b] = <ts, vId, blk>;
numberOfOccurences += 1;
}
else{
mCatches[b] = <[t], vId, b>;
}
}
}
return generateMultiCatches([mCatches[b] | b <- mCatches]);
}
/*
* Creates a syntactic catch clause (either a simple one or
* a multicatch).
*
* This is a recursive definition. The base case expects only
* one tuple, and than it returns a single catch clause. In the
* recursive definition, at least two tuples must be passed as
* arguments, and thus it returns at least two catches clauses
* (actually, one catch clause for each element in the list)
*/
private Catches generateMultiCatches([<ts, vId, b>]) = {
types = parse(#CatchType, intercalate("| ", ts));
return (Catches)`catch(<CatchType types> <VariableDeclaratorId vId>) <Block b>`;
};
private Catches generateMultiCatches([<ts, vId, b>, C*]) = {
catches = generateMultiCatches(C);
types = parse(#CatchType, intercalate("| ", ts));
return (Catches)`catch(<CatchType types> <VariableDeclaratorId vId>) <Block b> <CatchClause+ catches>`;
};
One way to do it is using a local variable and a block with an insert:
module MultiCatch
import lang::java::\syntax::Java18;
import ParseTree;
import IO;
import Map;
import Type;
import List;
/**
* Refactor a try-catch statement to use the
* MultiCatch construct of Java 7.
*/
public tuple[int, CompilationUnit] refactorMultiCatch(CompilationUnit unit) {
int numberOfOccurences = 0; /* the type is superfluous */
CompilationUnit cu = visit(unit) {
case (TryStatement)`try <Block b1> <Catches c1>` : {
numberOfOccurences += 1;
mc = computeMultiCatches(c1)
insert (TryStatement)`try <Block b1> <Catches mc>`;
}
};
return <numberOfOccurences, cu>;
}
The {...} block allows multiple statements to be executed after the match;
The local variable is now only present in the frame of refactorMultiCatch;
The insert statement has the same effect as the previous => arrow did;
Since the match := always succeeds, I changed the when clause into a simple assigment
There is also other more complex ways to share state in Rascal, but I personally prefer to have state not escape the lexical scope of a function.

How to discover lock declaration instruction in llvm?

I'm new to llvm , and was trying to find lock declaration statement and then do some instrumention work,the code like this:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int share = 42;
mutex m;
void f()
{
m.lock();
--share;
cout << "function f -> share: " << share << '\n';
m.unlock();
}
int main()
{
thread thf{f};
thf.join();
return 0;
}
I want to find the lock declaration instruction eg:
mutex m;
the llvm instrumention pass like this:
struct SkeletonPass : public FunctionPass {
static char ID;
SkeletonPass() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F) {
// Get the function to call from our runtime library.
LLVMContext &Ctx = F.getContext();
Constant *logFunc = F.getParent()->getOrInsertFunction(
"logop", Type::getVoidTy(Ctx), Type::getInt32Ty(Ctx), NULL
);
for (auto &B : F) {
for (auto &I : B) {
***if ((&I) is lock declaration instruction)*** {
// Insert something *after* `op`.
IRBuilder<> builder(op);
builder.SetInsertPoint(&B, ++builder.GetInsertPoint());
// Insert a call to function.
builder.CreateCall(logFunc, ConstantInt::get(Type::getInt32Ty(Ctx), 2));
return true;
}
}
}
In short, could you please tell me how to discover lock declaration instruction, thanks!
The declaration would appear as a global, so you should write a module pass to find it, not a function pass. It should appear as something like:
#m = global %mutex zeroinitializer
In fact, using the demo at http://ellcc.org/demo/index.cgi to try this, you can indeed see that:
...
%"class.std::__1::mutex" = type { %struct.pthread_mutex_t }
%struct.pthread_mutex_t = type { %union.anon }
%union.anon = type { [5 x i8*] }
...
#m = global %"class.std::__1::mutex" zeroinitializer, align 8
You can use LLVM's CppBackend to compile your code. This would produce a C++ code that makes up the source. You can then easily find out how mutex m; definition is constructed via LLVM API.
Run clang -march=cpp foo.cpp to use CppBackend. Alternatively, you can use this demo page to compile your code online.

LuaD class table copying

Consider this in D programming language:
import luad.all
class C1
{
auto l1 = new LuaState;
l1["somebool"] = true;
this()
~this()
}
class C2
{
C1 cc = new C1;
auto l2 = new LuaState;
// here I want to inject l1["somebool"] to l2
}
void main() { C2 cx = new C2; }
As a solution, it is possible that I make a local variable
bool var = cc.l1["somebool"]
and then insert it in l2 - but this does not seem to be the best solution.
Is there any way to copy one lua stack defined inside a class to another stack in another class?
I don't know much about LuaD or Lua, but you can extract globals into a struct as shown in the last example on this page. And then you can set the values from the struct into l2 state.
// warning: untested
struct State
{
bool somebool;
}
State state;
l1.globals.toStruct!State(state);
foreach (member; __traits(allMembers, State))
{
l2.globals.set(member, __traits(getMember, state, member));
}

boost python overload operator ()

I would like to bind the operator() using Boost::Python but I don't really see how to do this. Consider the example:
C++:
class Queuer
{
public:
void Queuer::operator()(const qfc::Queue & iq, const qfc::Message & im) const;
void Queuer::operator()(const qfc::Agent & ia, const qfc::Message & im) const;
// some other overloaded operator() methods
};
So in a Python script, after importing the module I'm using (called qfc), I would like to do:
Python:
>>> queuer = qfc.Queuer()
// instantiating a Message an Agent and a Queue object
>>> queuer(queue,message)
>>> queuer(agent,message)
>>> ...
Would you have any idea on how to do it? maybe with boost::python call<>?
Thank you,
Kevin
When exposing the Queuer class, define a __call__ method for each Queuer::operator() member function. Boost.Python will handle the appropriate dispatching based on types. The only complexity is introduced with pointer-to-member-function syntax, as the caller is required to disambiguate &Queuer::operator().
Additionally, when attempting to pass derived classes in Python to a C++ function with a parameter of the Base class, then some additional information needs to be exposed to Boost.Python:
The base C++ class needs to be exposed with class_. For example, class_<BaseType>("Base").
The derived class needs to explicitly list its base classes when being exposed with bases_. For example, class_<DerivedType, bases<BaseType> >("Derived"). With this information, Boost.Python can do proper casting while dispatching.
Here is a complete example:
#include <iostream>
#include <boost/python.hpp>
// Mockup classes.
struct AgentBase {};
struct MessageBase {};
struct QueueBase {};
struct SpamBase {};
struct Agent: AgentBase {};
struct Message: MessageBase {};
struct Queue: QueueBase {};
struct Spam: SpamBase {};
// Class with overloaded operator().
class Queuer
{
public:
void operator()(const AgentBase&, const MessageBase&) const
{
std::cout << "Queuer::operator() with Agent." << std::endl;
}
void operator()(const QueueBase&, const MessageBase&) const
{
std::cout << "Queuer::operator() with Queue." << std::endl;
}
void operator()(const SpamBase&, const MessageBase&) const
{
std::cout << "Queuer::operator() with Spam." << std::endl;
}
};
/// Depending on the overlaod signatures, helper types may make the
/// code slightly more readable by reducing pointer-to-member-function syntax.
template <typename A1>
struct queuer_overload
{
typedef void (Queuer::*type)(const A1&, const MessageBase&) const;
static type get(type fn) { return fn; }
};
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
// Expose only the base class types. Do not allow the classes to be
// directly initialized in Python.
python::class_<AgentBase >("AgentBase", python::no_init);
python::class_<MessageBase>("MessageBase", python::no_init);
python::class_<QueueBase >("QueueBase", python::no_init);
python::class_<SpamBase >("SpamBase", python::no_init);
// Expose the user types. These classes inerit from their respective
// base classes.
python::class_<Agent, python::bases<AgentBase> >("Agent");
python::class_<Message, python::bases<MessageBase> >("Message");
python::class_<Queue, python::bases<QueueBase> >("Queue");
python::class_<Spam, python::bases<SpamBase> >("Spam");
// Disambiguate via a varaible.
queuer_overload<AgentBase>::type queuer_op_agent = &Queuer::operator();
python::class_<Queuer>("Queuer")
// Disambiguate via a variable.
.def("__call__", queuer_op_agent)
// Disambiguate via a helper type.
.def("__call__", queuer_overload<QueueBase>::get(&Queuer::operator()))
// Disambiguate via explicit cast.
.def("__call__",
static_cast<void (Queuer::*)(const SpamBase&,
const MessageBase&) const>(
&Queuer::operator()))
;
}
And its usage:
>>> import example
>>> queuer = example.Queuer()
>>> queuer(example.Agent(), example.Message())
Queuer::operator() with Agent.
>>> queuer(example.Queue(), example.Message())
Queuer::operator() with Queue.
>>> queuer(example.Spam(), example.Message())
Queuer::operator() with Spam.
Thanks for your help.
Actually I've already tested the static cast solution. In reality, I need to pass a qfc::lqs::Message or qfc::lqs::Agent or qfc::lqs::Spam when invoking queuer(). qfc::lqs::Message for example, as for qfc::lqs::Agent inherit from qfc::Message and qfc::Agent respectively.
So can I "cast" qfc::lqs::Message, qfc::lqs::Agent and qfc::lqs::Spam to qfc::Message, qfc::Agent and qfc::Spam when invoking the operator() so that the signature corresponds to operator() ?
This to avoid the error shown below:
error: invalid static_cast from type '<unresolved overloaded function type>' to type 'void (qfc::lqs::Queuer::*)(const qfc::lqs::Queue&, const qfc::lqs::Message&)const'

CUDA 5.0: checkCudaErrors fails to find correct "check" method if class has a "check" method

As the cutil.h header is removed from CUDA Samples, some new headers are introduced like helper_cuda.h, helper_functions.h.
One of the main keywords that is used by me was CUDA_CHECK_ERROR, and I think it is replaced with checkCudaErrors.
In most of my code the macro compiles and works well. However when I use it in a class which has a function named check(..), checkCudaErrors function gives compile errors.
Here is an example:
#include <stdio.h>
#include <cuda_runtime.h>
#include <helper_cuda.h>
#include <helper_functions.h>
template<typename T>
class Trivial {
public:
void check()
{
}
void initialize()
{
checkCudaErrors(cudaMalloc(NULL, 1));
}
T val;
};
int main(int argc, char **argv)
{
Trivial<int> tt;
tt.initialize();
return 0;
}
and the result of compilation: (the same error is seen when compiled with GCC 4.5 also!)
1>------ Build started: Project: ZERO_CHECK, Configuration: Release x64 ------
2>------ Build started: Project: massivecc, Configuration: Release x64 ------
2> trivial_main.cpp
2>..\src\trivial_main.cpp(19): error C2660: 'Trivial<T>::check' : function does not take 4 arguments
2> with
2> [
2> T=int
2> ]
2> ..\src\trivial_main.cpp(18) : while compiling class template member function 'void Trivial<T>::initialize(void)'
2> with
2> [
2> T=int
2> ]
2> ..\src\trivial_main.cpp(29) : see reference to class template instantiation 'Trivial<T>' being compiled
2> with
2> [
2> T=int
2> ]
3>------ Skipped Build: Project: ALL_BUILD, Configuration: Release x64 ------
3>Project not selected to build for this solution configuration
========== Build: 1 succeeded, 1 failed, 1 up-to-date, 1 skipped ==========
The same error is taken when I removed the template parameter.
I had to copy the check(..) function's definition from helper_functions.h into my class's header to be able to compile the class.
#include <stdio.h>
#include <cuda_runtime.h>
#include <helper_cuda.h>
#include <helper_functions.h>
class Trivial {
public:
template< typename T >
bool check(T result, char const *const func, const char *const file, int const line)
{
if (result) {
fprintf(stderr, "CUDA error at %s:%d code=%d(%s) \"%s\" \n",
file, line, static_cast<unsigned int>(result), _cudaGetErrorEnum(result), func);
return true;
} else {
return false;
}
}
void check() { }
void initialize()
{
checkCudaErrors(cudaMalloc(NULL, 1));
}
};
int main(int argc, char **argv)
{
Trivial tt;
tt.initialize();
return 0;
}
So, this mainly solved my problem and my code compiled successfully.
with reference to the source code found in helper_cuda.h on line 680
https://github.com/pathscale/nvidia_sdk_samples/blob/master/vectorAdd/common/inc/helper_cuda.h
you find checkCudaErrors declares a #define checkCudaErrors(val) check ( (val), #val, FILE, LINE ) which takes in a single argument and calls check with 3 other arguments based on config.Note that it is also defined in line 680
Whereas in your case, you define a check that does not take any argument. case of different declaration and definition, multiple definitions.

Resources