help with python ctypes

Started by
2 comments, last by aryx 14 years, 1 month ago
I'm trying to call a C function using python ctypes. I want to pass and receive a struct from the function but am having a lot of trouble with it. I have a C dll with the following code:

-- test.h --
struct vec3f
{
	float x;
	float y;
	float z;
};

__declspec(dllexport) struct vec3f addvec(struct vec3f a, struct vec3f b);




-- test.c --
struct vec3f addvec(struct vec3f a, struct vec3f b)
{
	a.x += b.x;
	a.y += b.y;
	a.z += b.z;
	return a;
}


My python code looks like this:

-- tester.py --
from ctypes import *
import os
libtest = cdll.LoadLibrary(os.getcwd() + '/libpydlltest.dll')


class vec3f(Structure):
	_fields_ =  [("x", c_float),
				("y", c_float),
				("z", c_float)]
libtest.addvec.argtypes = [vec3f, vec3f]
libtest.addvec.restype = vec3f
				
a = vec3f(10, 15, 20)
b = vec3f(4, 5, 6)

print a.x, a.y, a.z
print b.x, b.y, b.z

a = libtest.addvec(a,b)

print a.x, a.y, a.z


The problem is, when I run my python script, I get the following error:
Quote: Traceback (most recent call last): File "tester.py", line 20, in <module> a = libtest.addvec(a,b) ValueError: Procedure called with not enough arguments (4 bytes missing) or wrong calling convention
Advertisement
The latter part of the error message may be your issue (wrong calling convention). Perhaps give windll.LoadLibrary a try. Let me know if that works.
Odd...

I replaced cdll.LoadLibrary with windll.LoadLibrary and got the following message:

Quote:
Traceback (most recent call last):
File "tester.py", line 9, in <module>
print libtest.add(a, b)
ValueError: Procedure probably called with too many arguments (8 bytes in excess)
Hmm, I'm not particularly familiar with ctypes, but I'll see what I can do to help you out some. I was reading through the documentation and when I came across the section on structure alignment, I was thinking that this may be your issue. If your DLL is packing things together tightly, and ctypes is packing things together on 8-byte boundaries, that would explain the "8 bytes in excess" (4 for each argument). The best advice I can give at the moment is to play around with the structure packing.

P.S. I quickly copied and pasted your code and it works fine on OS X, so it's just a simple little calling convention/packing issues I would expect.

[Edited by - aryx on March 1, 2010 5:03:55 AM]

This topic is closed to new replies.

Advertisement