PSP Programming/General/Common Callback

Common Callback edit

Before we begin programming for the PSP, we will start by creating a folder named “common” in our programming directory. This folder will contain several files which will often be used in our programs. We'll put these files here so that we don't constantly have to write the same code over and over again.

callback.h edit

Now let's create a new file with the name "callback.h". This header file will declare some of the stuff needed so that we can get our program to run on the PSP.

#ifndef COMMON_CALLBACK_H
#define COMMON_CALLBACK_H

int isRunning();
int setupExitCallback();

#endif

The 'ifndef' is used to make sure that this file only gets imported once, otherwise an error will occur. Then it should be pretty self-explanatory; we will have two functions which we will use: "isRunning()" to check if the user has requested to quit the program, and "setupCallbacks()" which will setup all the necessary things for your program to run on the PSP.

callback.c edit

Now that we have the header definitions we can also create the source file: name it "callback.c". We'll start by including the file "pspkernel.h" which gives us access to several kernel methods.

#include <pspkernel.h>

Next we create a boolean. Executing the method "isRunning()" will tell us whether a request to exit the application was created by the user. We will use this function in our program so that we can clean up any leftover memory, and exit gracefully.

static int exitRequest  = 0;

int isRunning()
{
	return !exitRequest;
}

Now this is where the hard part comes in... the good news, is that you don't need to completely understand it! Essentially what it does is create a new thread, which will create an exit callback. The callback will then make "exitRequest" equal to true if the user presses the "home" and "exit" button on the PSP. See for yourself:

#include <pspkernel.h>

static int exitRequest = 0;

int isRunning() 
{ 
	return !exitRequest; 
}

int exitCallback(int arg1, int arg2, void *common) 
{ 
	exitRequest = 1; 
	return 0; 
}

int callbackThread(SceSize args, void *argp) 
{ 
	int callbackID;

	callbackID = sceKernelCreateCallback("Exit Callback", exitCallback, NULL); 
	sceKernelRegisterExitCallback(callbackID);

	sceKernelSleepThreadCB();

	return 0; 
}

int setupExitCallback() 
{ 
	int threadID = 0;

	threadID = sceKernelCreateThread("Callback Update Thread", callbackThread, 0x11, 0xFA0, THREAD_ATTR_USER, 0); 
	 
	if(threadID >= 0) 
	{ 
		sceKernelStartThread(threadID, 0, 0); 
	}

	return threadID; 
}

Don't worry if you don't completely understand it, that's why we created a separate file for it. It's not going to change, so all we have to do is include it.

Now you can go into the next section, which will show you how to create a simple "Hello World!" program.