C++ extension for Python - floats coming back as integers?

Started by
4 comments, last by GarrickW 12 years, 11 months ago
So I'm getting into C++ at the moment, and trying to figure how to make extensions in C++ for my main project, which is so far mostly in Python, so that I can put the more processor-intensive aspects of the game in C++ code.

I've figured out how to get a C++ .dll file to interact properly with Python (thanks to this tutorial), but now I'm having an odd problem when trying to expand on the tutorial. I've got the following C++ code which, as you can probably guess, is meant to calculate the distance between two points on a Cartesian plane.

#include <cmath>
#include <cstdlib>
#define DLLEXPORT extern "C" __declspec(dllexport)

DLLEXPORT int dist(int xStart, int xTarg, int yStart, int yTarg)
{
float distance;
int xDist = abs(xTarg - xStart);
int yDist = abs(yTarg - yStart);
distance = sqrt((pow(xDist, 2)) + (pow(yDist, 2)));
return distance;
}


And the following code on the Python side of things.

from ctypes import cdll

mydll = cdll.LoadLibrary("mymath.dll")

startPoint = (8, 7)
targPoint = (6, 5)

print mydll.dist(startPoint[0], targPoint[0], startPoint[1], targPoint[1])


Yet when I run the Python code, the result I get is 2, not the 2.828 you'd expect. I'm sure I'm just missing something minor, here. How do I get the dist() function to return a float to Python? distance is already declared as a float in the C++ code. Running print float(...) rather than just print only returns 2.0. I did consider that maybe I should declare the dist function using float rather than int, but then the result I get is a bizarrely high float, a little over 10,000.

Can someone point out what I'm doing wrong?
Advertisement
Well, I'd start by declaring your C function to return a float rather than an int.
I tried doing that as well, but then the answer I get is 1077216499.

At least, I think that's what I tried.

DLLEXPORT float dist2(int xStart, int xTarg, int yStart, int yTarg)
{
float distance;
int xDist = abs(xTarg - xStart);
int yDist = abs(yTarg - yStart);
distance = sqrt((pow(xDist, 2)) + (pow(yDist, 2)));
return distance;
}
Dealing with return types with the ctypes module.
Ah - thanks for that! Let's see...
Thanks! I've gone ahead and implemented those ideas, and now it works.

For reference, here is the final code:

#include <cmath>
#include <cstdlib>
#define DLLEXPORT extern "C" __declspec(dllexport)

DLLEXPORT float dist(int xStart, int xTarg, int yStart, int yTarg)
{
float distance;
int xDist = abs(xTarg - xStart);
int yDist = abs(yTarg - yStart);
distance = sqrt((pow(xDist, 2)) + (pow(yDist, 2)));
return distance;
}


from ctypes import *

mydll = cdll.LoadLibrary("mymath.dll")
distance = mydll.dist2
distance.restype = c_float

startPoint = (8, 7)
targPoint = (6, 5)

print distance(startPoint[0], targPoint[0], startPoint[1], targPoint[1])

This topic is closed to new replies.

Advertisement