I'm trying to create my own functions for ReadProcessMemory and WriteProcessMemory in VisualC++ so I don't have to keep inputting all the info for every time I create a new function call. This project is Windows Form. Here's the problem
void Read(DWORD Add, int Value);
private: System::Void btnP1Money_Click_1(System::Object^ sender, System::EventArgs^e)
{
int BigMoney = 100000;
int GetMoneyValue;
DWORD MonAddr = 0x180A6C8;
Read(MonAddr, GetMoneyValue);
}
void Read(DWORD Add, int Value)
{
HWND window = FindWindow(0, _T("Process Window Name"));
DWORD pID = NULL;
DWORD base = dwGetModuleBaseAddress(pID, _T("Game.exe"));
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pID);
GetWindowThreadProcessId(window, &pID);
ReadProcessMemory(handle, (LPCVOID)(base+Add), &Value, 4, NULL);
}
The value in game is 500, yet the value returned from Read() is 0. Not sure what I'm doing wrong. I just don't want to have to define everything in my Read() function everytime on each button click and checkbox tick ect.
Thanks
You should modify the Read header to
void Read(DWORD Add, int& Value)
I've written small example which works. Make sure that you check the content of the variable, not it's address
void Read(int& Value)
{
Value++;
}
int main(array<System::String ^> ^args)
{
int GetMoneyValue = 5;
Read(GetMoneyValue);
Console::WriteLine(GetMoneyValue);
//6;
return 0;
}
You need to pass by reference, otherwise the function gets its own copy of the int:
void Read(DWORD Add, int& Value);
Alternatively, you could return the value:
int Read(DWORD Add, int Value)
{
....
return Value;
}
Related
I would like to express something like this in Critcl:
void setter(int* grid, int value, int x, int y) {
grid[xy2addr(x,y)] = value;
}
I'm in particular stuck on how to deal with int* grid in Critcl. object? bytes? Custom type maybe?
Related to this question.
This case doesn't map very well onto Tcl's value model. The issue is that grid is (a pointer to) an updateable value collection. There are two ways of modelling this in Tcl in general:
As an opaque object.
As a variable containing a Tcl list (since in model terms, while Tcl values are thought of as immutable, Tcl variables are mutable).
I'll describe how to do both below, but I'm guessing that you're going to be thinking of these zOrder things as a distinct mutable type and that the additional modest one-time overhead of making the custom type will suit you far better.
Opaque (Mutable) Objects
When working with opaque objects, you pass handles to them (basically just a name) around and then you unpack them as a custom Critcl type. The trick is to create some helper functions in C to do the mapping (this can be in a critcl::ccode command) that does the mapping between names and pointers. This is slightly messy to do, but is just about building a couple of hash tables.
critcl::ccode {
static Tcl_HashTable *zOrderMap = NULL, *zOrderRevMap = NULL;
static Tcl_Obj *
MakeZOrderObj(int *zOrder) {
/* Initialize the two maps, if needed */
if (zOrderMap == NULL) {
zOrderMap = (Tcl_HashTable *) Tcl_Alloc(sizeof(Tcl_HashTable));
Tcl_InitObjHashTable(zOrderMap);
zOrderRevMap = (Tcl_HashTable *) Tcl_Alloc(sizeof(Tcl_HashTable));
Tcl_InitHashTable(zOrderRevMap, TCL_ONE_WORD_KEYS);
}
int isNew;
Tcl_HashEntry *hPtr = Tcl_FindHashEntry(zOrderRevMap, (char*) zOrder, &isNew);
if (!isNew) {
return Tcl_GetHashValue(hPtr);
}
/* make a handle! */
Tcl_Obj *handle = Tcl_ObjPrintf("zOrder%ld", (long) zOrder);
Tcl_SetHashValue(hPtr, handle);
Tcl_IncrRefCount(handle);
hPtr = Tcl_CreateHashEntry(zOrderMap, (char*) handle, &isNew);
Tcl_SetHashValue(hPtr, zOrder);
return handle;
}
static int
GetZOrderFromObj(Tcl_Interp *interp, Tcl_Obj *objPtr, int **zOrderPtr) {
Tcl_HashTable *hPtr;
if (!zOrderMap || (hPtr = Tcl_FindHashEntry(zOrderMap, (char *) objPtr)) == NULL) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf("no such zOrder \"%s\"",
Tcl_GetString(objPtr)));
return TCL_ERROR;
}
*zOrderPtr = (int *) Tcl_GetHashValue(hPtr);
return TCL_OK;
}
}
With that helper code in place, you can then define a custom Critcl type like this:
critcl::argtype zOrder {
if (GetZOrderFromObj(interp, ##, #A) != TCL_OK) {
return TCL_ERROR;
}
} int*
critcl::resulttype zOrder {
if (rv == NULL) {
return TCL_ERROR;
}
Tcl_SetObjResult(interp, MakeZOrderObj(rv));
return TCL_OK;
} int*
That then lets you write your real code as something like this. Note that grid is defined as being of (custom) type zOrder, and that those can only be manufactured by some code that returns a zOrder as its result.
critcl::cproc setter {zOrder grid int value int x int y} void {
grid[xy2addr(x,y)] = value;
}
(The deletion function that removes the entries from the hash tables and deletes the C array is left as an exercise.)
Tcl List Variable
The other way of doing this is to make zOrder values be held in Tcl variables as lists of integers. This can be nice because it lets you look inside easily, but it can also be not so nice in other ways, as the code is not constrained to work with proper values and you expose your cprocs to more details of what's happening in Tcl.
critcl::cproc setter {Tcl_Interp* interp object varName int value int x int y} ok {
/* Unpack the list of ints from the variable */
Tcl_Obj *listObj = Tcl_ObjGetVar2(interp, varName, NULL, TCL_LEAVE_ERR_MSG);
if (listObj == NULL)
return TCL_ERROR;
Tcl_Obj **listv; int listc;
if (Tcl_ListObjGetElements(interp, listObj, &listc, &listv) != TCL_OK)
return TCL_ERROR;
int *grid = alloca(sizeof(int) * listc);
for (int i=0; i<listc; i++)
if (Tcl_GetIntFromObj(interp, listv[i], &grid[i]) != TCL_OK)
return TCL_ERROR;
/* The core of the functionality */
grid[xy2addr(x,y)] = value;
/* Repack the list of ints from the variable; this code could be optimized in this case! */
for (int i=0; i<listc; i++)
listv[i] = Tcl_NewIntObj(grid[i]);
listObj = Tcl_NewListObj(listc, listv);
Tcl_ObjSetVar2(interp, varName, NULL, listObj, 0);
return TCL_OK;
}
I would like to pass to a function a reference to a class method.
For example:
#include <functional>
struct Foo
{
int f(const int& val) const
{
return val+2;
}
};
int caller(const std::function<int(const int&)>& f)
{
return f(1);
}
int main()
{
caller([](const int& val){return val+2;}); // OK
Foo foo;
caller(foo.f); // WRONG
return 0;
}
How can I fix the second call of caller() (NB: Foo:f() is not static)?
In your case, function f doesn't use any member of Foo so it can be declared static
static int f(const int& val)
and passed as:
caller(&Foo::f);
But suppose that f cannot be declared static and you want to pass "reference" to member function of particular object.
You can use lambda in that case:
Foo foo;
caller(
[&foo](const int& val){
return foo.f(val);
}
);
foo object is captured in square brackets (in this case by reference) so that you can call f member function on that particular object.
Although it is not part of your question, I should add that it is not really useful to pass int by const reference, as you will not gain any performance improvement that way. Actually, your code will run slower than if you pass int by value.
I'm trying to create a ScrollView class with cocos2d-2.0-rc2-x-2.0.1 and I mean to do something in update function to implement the auto-scroll effect.Unfortunately,I find the function has never been called.Though I've done a lot of work like searching on the internet,debuging step by step and so on,the possible solutions I found helped little.
As far as I know,my ScrollView class derive from CCNode and I've implemented the update function.The declaration of ScrollView is as following:
class ScrollView:public CCNode,public CCTouchDelegate
{
ClippingNode* visible_view;
CCNode* content_view;
//CCArray* items;
float row_margin;
float col_margin;
float interval_margin;
float last_y;//起始y方向坐标
float interval_dis;//间隔时间段内y方向上的位移。
bool touch_stopped;//标识触摸是否停止,主要用于自动滚动。
float up_bounder_y,down_bounder_y;//content_view的y方向坐标上下限
int items_num;
public:
static ScrollView* New(CCSize visible_view_size,float row_margin,float col_margin,float interval_margin,CCNode* background = NULL);
void ccTouchBegin(cocos2d::CCNode *node,const cocos2d::CCPoint &point);
void ccTouchMove(cocos2d::CCNode *node,const cocos2d::CCPoint &point);
void ccTouchEnd(cocos2d::CCNode *node,const cocos2d::CCPoint &point);
virtual void onEnter();
protected:
CCNode* makeCard();
void initContent();
private:
ScrollView():visible_view(NULL),content_view(NULL),touch_stopped(true){}
virtual ~ScrollView();
bool init(CCSize visible_view_size,float row_margin,float col_margin,float interval_margin,CCNode* background);
void update(float dt);
};
And here is the definition of update function:
void ScrollView::update(float dt)
{
CCLOG("update");
if(touch_stopped)
{
if(abs(interval_dis) < a)
{
interval_dis = 0.0f;
this->unscheduleUpdate();
}else
{
if(interval_dis < 0)
interval_dis += a;
else
interval_dis -= a;
const float future_y = content_view->getPositionY() + interval_dis;
if(future_y > down_bounder_y && future_y < up_bounder_y)
{
content_view->setPositionY(interval_dis);
}else if(future_y <= down_bounder_y)
{
content_view->setPositionY(down_bounder_y);
interval_dis = 0.0f;
}else
{
content_view->setPositionY(up_bounder_y);
interval_dis = 0.0f;
}
}
}
}
So I can ensure the type of the param is float instead of CCTime or ccTime which may cause update function never to be called.Moreover,I invoke the scheduleUpdate in the init method like the following:
bool ScrollView::init(CCSize visible_view_size,float row_margin,float col_margin,float interval_margin,CCNode* background)
{
visible_view = ClippingNode::New(visible_view_size);
CHECK_RETURN(visible_view,NULL,false);
visible_view->retain();
content_view = CCNode::create();//node函数中已调用autorelease
CHECK_RETURN(content_view,NULL,false);
content_view->retain();
this->row_margin = row_margin;
this->col_margin = col_margin;
this->interval_margin = interval_margin;
this->setAnchorPoint(ccp(0.5f,0.5f));
this->setContentSize(visible_view_size);
visible_view->setPosition(0,0);
content_view->setAnchorPoint(ccp(0,1));
content_view->setPosition(row_margin,visible_view_size.height);
content_view->setContentSize(CCSize(visible_view_size.width - 2 * row_margin,2 * col_margin));
this->addChild(visible_view);
visible_view->addChild(content_view);
down_bounder_y = visible_view_size.height;
up_bounder_y = content_view->getContentSize().height > visible_view_size.height?content_view->getContentSize().height:visible_view_size.height;
UserData* user_data = UserData::getUserData(this,true);
CHECK_RETURN(user_data,NULL,false);
user_data->setContainer(true);
items_num = 0;
initContent();
if(background)
{
background->setScaleX(visible_view_size.width/background->getContentSize().width);
background->setScaleY(visible_view_size.height/background->getContentSize().height);
background->setAnchorPoint(ccp(0.5f,0.5f));
background->setPosition(visible_view_size.width/2,visible_view_size.height/2);
user_data = UserData::getUserData(background,true);
user_data->setHitable(false);
this->addChild(background,-1);
}
this->scheduleUpdate();
return true;
}
Through debug,I can ensure the sentence "this->scheduleUpdate()" is invoked.In addition,I created a ScrollView object named scroll_view and added it to the main node through addChild function.So,where am I wrong?Any addvice would be appreciated and thanks for watching:p
I forgot to invoke the CCNode::onEnter in my own onEnter function. Thus all we need to do is invoke CCNode::onEnter in the ScrollView::onEnter. Hope other people don't make the mistake as I did.
If you invoke the onEnter, scheduleUpdate() may be not working.
CCDirector::sharedDirector()->getScheduler()->scheduleUpdateForTarget(this,0,false);
or
CCDirector::sharedDirector()->getScheduler()->scheduleSelector(schedule_selector(NewGame::update),this,0.1,false);
Dont know why your code is not working but have you tried this:
CCDirector::sharedDirector()->getScheduler()->scheduleUpdateForTarget(cocos2d::CCObject *pTarget, int nPriority, bool bPaused);
you can check whether the node responds to update() call using:
pNode->getIsRunning();
I wrote QSQLTableModel inheritor for working with qml and it's work well. I need use it with QTableView too, data shows, but I cannot modify it - when I edit everything is ok, but all changes drop when I get out from field (I know about editStrategy, but the problem occurs earlier). I suppose that something wrong with virtual function, but I cant undestant what. If i create QSqlTableModel with the same parameters, everything is ok. Somebody have any idea how can i fix this? My code:
h:
class ListModel : public QSqlTableModel
{
Q_OBJECT
Q_PROPERTY( int count READ rowCount() NOTIFY countChanged())
signals:
void countChanged();
public:
Q_INVOKABLE QVariant data(const QModelIndex &index, int role) const;
ListModel(QObject *parent, QSqlDatabase _db):QSqlTableModel(parent,_db){this->setEditStrategy(QSqlTableModel::OnManualSubmit);}
void applyRoles();
#ifdef HAVE_QT5
virtual QHash<int, QByteArray> roleNames() const{return roles;}
#endif
private:
int count;
QHash<int, QByteArray> roles;
};
cpp:
//based on http://qt-project.org/wiki/How_to_use_a_QSqlQueryModel_in_QML
void ListModel::applyRoles()
{
roles.clear();
qDebug()<<"\n"<<this->tableName();
for (int i = 0; i < this->columnCount(); i++) {
QString role=this->headerData(i, Qt::Horizontal).toString();
roles[Qt::UserRole + i + 1] = QVariant(role).toByteArray();
qDebug()<<this->headerData(i, Qt::Horizontal);
}
#ifndef HAVE_QT5
setRoleNames(roles);
#endif
}
QVariant ListModel::data(const QModelIndex &index, int role) const{
QVariant value;
if(role < Qt::UserRole)
{
value = QSqlQueryModel::data(index, role);
}
else {
int columnIdx = role - Qt::UserRole - 1;
QModelIndex modelIndex = this->index(index.row(), columnIdx);
value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}
return value;
}
UPD
I understood that the problem is in data method's quantifier const, if I remove it everything is ok with QTableView, but I cant get data from model with gml's listviews. I see only one solution - replace interition from QSqlTableModel with aggregation it, but maybe someone knows better solution?
Summary: Solved with strange hack - inherited from QSqlRelationalTableModel instead QSqlTableModel, I think the reason is that QSqlRelationalTableModel has rewritten non virtual method data
I have a trouble working with JCUDA. I have a task to make 1D FFT using CUFFT library, but the result should be multiply on 2. So I decided to make 1D FFT with type CUFFT_R2C. Class responsible for this going next:
public class FFTTransformer {
private Pointer inputDataPointer;
private Pointer outputDataPointer;
private int fftType;
private float[] inputData;
private float[] outputData;
private int batchSize = 1;
public FFTTransformer (int type, float[] inputData) {
this.fftType = type;
this.inputData = inputData;
inputDataPointer = new CUdeviceptr();
JCuda.cudaMalloc(inputDataPointer, inputData.length * Sizeof.FLOAT);
JCuda.cudaMemcpy(inputDataPointer, Pointer.to(inputData),
inputData.length * Sizeof.FLOAT, cudaMemcpyKind.cudaMemcpyHostToDevice);
outputDataPointer = new CUdeviceptr();
JCuda.cudaMalloc(outputDataPointer, (inputData.length + 2) * Sizeof.FLOAT);
}
public Pointer getInputDataPointer() {
return inputDataPointer;
}
public Pointer getOutputDataPointer() {
return outputDataPointer;
}
public int getFftType() {
return fftType;
}
public void setFftType(int fftType) {
this.fftType = fftType;
}
public float[] getInputData() {
return inputData;
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
public float[] getOutputData() {
return outputData;
}
private void R2CTransform() {
cufftHandle plan = new cufftHandle();
JCufft.cufftPlan1d(plan, inputData.length, cufftType.CUFFT_R2C, batchSize);
JCufft.cufftExecR2C(plan, inputDataPointer, outputDataPointer);
JCufft.cufftDestroy(plan);
}
private void C2CTransform(){
cufftHandle plan = new cufftHandle();
JCufft.cufftPlan1d(plan, inputData.length, cufftType.CUFFT_C2C, batchSize);
JCufft.cufftExecC2C(plan, inputDataPointer, outputDataPointer, fftType);
JCufft.cufftDestroy(plan);
}
public void transform(){
if (fftType == JCufft.CUFFT_FORWARD) {
R2CTransform();
} else {
C2CTransform();
}
}
public float[] getFFTResult() {
outputData = new float[inputData.length + 2];
JCuda.cudaMemcpy(Pointer.to(outputData), outputDataPointer,
outputData.length * Sizeof.FLOAT, cudaMemcpyKind.cudaMemcpyDeviceToHost);
return outputData;
}
public void releaseGPUResources(){
JCuda.cudaFree(inputDataPointer);
JCuda.cudaFree(outputDataPointer);
}
public static void main(String... args) {
float[] inputData = new float[65536];
for(int i = 0; i < inputData.length; i++) {
inputData[i] = (float) Math.sin(i);
}
FFTTransformer transformer = new FFTTransformer(JCufft.CUFFT_FORWARD, inputData);
transformer.transform();
float[] result = transformer.getFFTResult();
HilbertSpectrumTicksKernelInvoker.multiplyOn2(transformer.getOutputDataPointer(), inputData.length+2);
transformer.releaseGPUResources();
}
}
Method which responsible for multiplying uses cuda kernel function.
Java method code:
public static void multiplyOn2(Pointer inputDataPointer, int dataSize){
// Enable exceptions and omit all subsequent error checks
JCudaDriver.setExceptionsEnabled(true);
// Create the PTX file by calling the NVCC
String ptxFileName = null;
try {
ptxFileName = FileService.preparePtxFile("resources\\HilbertSpectrumTicksKernel.cu");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Initialize the driver and create a context for the first device.
cuInit(0);
CUdevice device = new CUdevice();
cuDeviceGet(device, 0);
CUcontext context = new CUcontext();
cuCtxCreate(context, 0, device);
// Load the ptx file.
CUmodule module = new CUmodule();
cuModuleLoad(module, ptxFileName);
// Obtain a function pointer to the "add" function.
CUfunction function = new CUfunction();
cuModuleGetFunction(function, module, "calcSpectrumSamples");
// Set up the kernel parameters: A pointer to an array
// of pointers which point to the actual values.
int N = (dataSize + 1) / 2 + 1;
int pair = (dataSize + 1) % 2 > 0 ? 1 : -1;
Pointer kernelParameters = Pointer.to(Pointer.to(inputDataPointer),
Pointer.to(new int[] { dataSize }),
Pointer.to(new int[] { N }), Pointer.to(new int[] { pair }));
// Call the kernel function.
int blockSizeX = 128;
int gridSizeX = (int) Math.ceil((double) dataSize / blockSizeX);
cuLaunchKernel(function, gridSizeX, 1, 1, // Grid dimension
blockSizeX, 1, 1, // Block dimension
0, null, // Shared memory size and stream
kernelParameters, null // Kernel- and extra parameters
);
cuCtxSynchronize();
// Allocate host output memory and copy the device output
// to the host.
float freq[] = new float[dataSize];
cuMemcpyDtoH(Pointer.to(freq), (CUdeviceptr)inputDataPointer, dataSize
* Sizeof.FLOAT);
And the kernel function is next:
extern "C"
__global__ void calcSpectrumSamples(float* complexData, int dataSize, int N, int pair) {
int i = threadIdx.x + blockIdx.x * blockDim.x;
if(i >= dataSize) return;
complexData[i] = complexData[i] * 2;
}
But when I'm trying to pass the pointer which points to the result of FFT (in device memory) to the multiplyOn2 method, it throws the exception on cuCtxSynchronize() call. Exception:
Exception in thread "main" jcuda.CudaException: CUDA_ERROR_UNKNOWN
at jcuda.driver.JCudaDriver.checkResult(JCudaDriver.java:263)
at jcuda.driver.JCudaDriver.cuCtxSynchronize(JCudaDriver.java:1709)
at com.ifntung.cufft.HilbertSpectrumTicksKernelInvoker.multiplyOn2(HilbertSpectrumTicksKernelInvoker.java:73)
at com.ifntung.cufft.FFTTransformer.main(FFTTransformer.java:123)
I was trying to do the same using Visual Studion C++ and there no problems with this. Could you please help me.
P.S.
I can solve this prolem, but I need to copy data from device memory to host memory and then copy back with creating new pointers every time before calling new cuda functions, which slows my program executing.
Where exactly does the error occurs at which line?
The Cuda error can also be a previous error.
Why do you use Pointer.to(inputDataPointer), you already have that device pointer. Now you pass a pointer to the device pointer to the device?
Pointer kernelParameters = Pointer.to(Pointer.to(inputDataPointer),
I also recommend to use "this" qualifier or any other marking to detect instance variables. I hate and refuse to look through code, especially as nested and long as your example if I cannot see which scope the variable in methods have trying to debug it by just reading it.
I don't wanna ask myself always where the hell comes this variable from.
If a complex code in a question at SO is not formatted properly I don't read it.