Ptyon ctypes - data row access in Structure.value is not performed

I can get the structure populated as a result of the DLL function (what it looks like in it using x=buffer(MyData) and then repr(str(buffer(x))) .

But an error occurs if I try to access the elements of the Structure using .value .

I have VarDefs.h which requires a structure like this:

 typedef struct { char Var1[8+1]; char Var2[11+1]; char Var3[3+1]; ... }TMyData 

which should be passed to such a function:

 __declspec(dllexport) int AFunction(TOtherData *OtherData, TMyData *MyData); 

In Python, I can now declare a structure this way (thanks to Mr. Martelli: see here Python ctypes - dll function for accepting structural failures ):

 class TMyData( Structure ): _fields_ = [ ("Var1" , type( create_string_buffer(9) ) ), ("Var2" , type( create_string_buffer(12)) ), ... 

I call the function as follows: result = Afunction( byref(OtherData) , byref(MyData ) )

As I said, when I try to access MyData.Var1.value , I get an error message (sorry, now could not be more specific!), But repr(str(x)) , where x is a copy of buffer(MyData) shows that in it!

How can I do it? Thanks!

+4
source share
2 answers

The structure you are trying to use ctypes for interaction contains several "character arrays" rather than "pointers to character arrays." Instead of using create_string_buffer(9) you need to use ctypes.c_char * 9 .

 class TMyData( ctypes.Structure ): _fields_ = [ ("Var1", ctypes.c_char * 9), ("Var2", ctypes.c_char * 12), ... ] 
+3
source

Just use print MyData.Var1 . An array of characters is converted to a Python string type when accessed through an instance of Structure that does not have a .value method.

Robust, working example:

DLL code (xc compiled with MSVC with "cl / LD xc")

 #include <string.h> typedef struct { char Var1[5]; char Var2[10]; char Var3[15]; } TMyData; __declspec(dllexport) int AFunction(TMyData *MyData) { strcpy(MyData->Var1,"four"); strcpy(MyData->Var2,"--nine---"); strcpy(MyData->Var3,"---fourteen---"); return 3; } 

Python code

 import ctypes as c class TMyData(c.Structure): _fields_ = [ ("Var1", c.c_char * 5), ("Var2", c.c_char * 10), ("Var3", c.c_char * 15)] lib = c.CDLL('x') data = TMyData() lib.AFunction(c.byref(data)) print data.Var1 print data.Var2 print data.Var3 print data.Var1.value # error! 

Output

 four --nine--- ---fourteen--- Traceback (most recent call last): File "C:\Python26\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 436, in ImportFile my_reload(sys.modules[modName]) File "C:\x.py", line 12, in <module> print data.Var1.value AttributeError: 'str' object has no attribute 'value' 
+3
source

All Articles