Skip to main content
gamedev.net
🔒 Locked

Pointers with SWIG and Python

Started by Prodigal Squirrel Apr 10, 2006 at 12:48 PM 0 replies 1.1k views
Original Post
Prodigal Squirrel
Prodigal Squirrel
I'm wrapping a c++ function with SWIG. Everything works fine, until I actually use the c++ module I create. When I attempt to call the function in python, I get an error involving one the pointer parameters. Here's all the error and the code:
---- Error ----
TypeError: in method 'particleUpdate', argument 1 of type 'int *'

---- The python test program ---- 
import particleSys

x = 3
y = 3
lifetime = 10
speed = 1.7
angle = 180

particleSys.particleUpdate(x, y, angle, speed, lifetime)

print x, y, angle, speed, lifetime

---- particleSys.c++ -----
#define PI 3.14159265

void particleUpdate(int *x, int *y, int angle, float speed, int *lifetime)
{
	float angleRad = (float)(angle*(PI/180));
	int dx = (int)(speed*cos(angleRad));
	int dy = (int)(-speed*sin(angleRad));
	*x += dx;
	*y += dy;
	*lifetime--;
}
I've been reading on SWIG, and I don't believe that it handles pointer arguments differently than normal ones, so I don't have a clue what the problem is.
-------------------------- Alex--------------------------
Gorg
Gorg
You are both right and wrong.

By default, swig will not change its behavior when wrapping the function, but this actually mean that it will want a pointer to an int and not a plain int.

Which means the only way you could use this function is if you called another wrapped function that returned an int* and used that value as an argument.

In your case, you have an input/output parameter. You must tell swig about that so it properly wraps the function. You do this using typemaps. Typemaps tell swigs how to do certain action like handling input and output parameters.

In the case of python, this means that your function in the interface file would look like this:

%include <typemaps.i>void particleUpdate(int *INOUT, int *INOUT, int angle, float speed, int *INOUT);


typemaps.i contains typemaps like the basic types in C++. There are also other files for the stl.

In python, the value passed in the function will not be modified, but you will receive a tuple has a return value.

x = 3y = 3lifetime = 10speed = 1.7angle = 180x,y,lifetime = particleUpdate(x,y,angle, speed, lifetime)print x, y, angle, speed, lifetime


The documentation is pretty vague on typemaps, but looking at the actual typemaps files helps. So I will point you to your swig folder under lib/python. Look at typemaps.i.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.