C_API - can't figure out setUserdata

Hey everyone,

I'm new to C programming in general and having a tough time passing data w/ setUserdata. Are there any tutorials out there on how to set this up properly? I'm getting all kinds of errors related to pointers and then when I fix them, it crashes.

Here's a sample of my code:

struct carData {
int yDiff;
};

static void updateEnemyCar(LCDSprite* s)
{
struct CarData* carDataLocal = (struct CarData*) pd->sprite->getUserdata(s);
int yDiff = carDataLocal->yDiff;
}

static LCDSprite* createEnemyCar(int xPos, int yPos)
{
int startingYDiff = abs(-280 - yPos);
struct CarData* carDataLocal;
carDataLocal->yDiff = startingYDiff;
pd->sprite->setUserdata(car, (void*) carDataLocal);
}

Thanks in advance,
Jeebs

Hello Jeebs,

It looks like you're mostly there - you are just missing allocating on the heap some a space to hold the CarData.

struct CarData* carDataLocal = pd->system->realloc(NULL, sizeof(struct CarData));

Remember to delete this when you're done with it (realloc the size of the memory location at the pointer to size 0)

This is assuming that CarData will get more data members in the future. If you really only need to pass one number then you can directly cast your yDiff value as (void*) as a simpler alternative.

1 Like

That worked, thanks Tim!