C Structure rebuild with ctypes

Georg nobody at nowhere.org
Mon Dec 21 18:09:49 EST 2009


Hi Mark,

many thanks for your help. I tried your code in my program and it worked.

I would like to understand what the code is doing and I have some questions 
to it.

> Are you passing in these values, or are they being returned?  To me the 
> depth of the pointer references implies numVars, varNames, and varTypes 
> are out parameters. I'll assume that for now.  If they are in/out 
> parameters let me know.

Your exactly right: the parameters numVars, varNames and VarTypes are out
paramters.

> I mocked up a DLL to test returning values of these types.  I used VS2008 
> and compiled with "cl /LD func.c":
>
> --- func.c -------------------------------
> #include <stdlib.h>
> #define FUNCDLL
> #include "func.h"
>
> static char* g_data[] = {"one","two","three"};
> static int g_types[] = {1,2,3};
>
> FUNCAPI int func (int handle, int *numVars, char ***varNames, int 
> **varTypes)
> {
> *numVars = _countof(g_data);
> *varNames = g_data;
> *varTypes = g_types;
> return handle + 1;
> }

What does the signature FUNCAPI do in this context?


>
>
> --- func.h -------------------------------
> #ifdef FUNCDLL
> #    define FUNCAPI __declspec(dllexport)
> #else
> #    define FUNCAPI __declspec(dllimport)
> #endif
>
> FUNCAPI int func (int handle, int *numVars, char ***varNames, int 
> **varTypes);
>

Do I need to wrap the compiled DLL file this way? I can load the DLL with 
the CDLL method, make calls to simple functions, e.g. no parameters, 
returning stirng and get the right values.


I added all the code from your func.py module to the code I already had. 
And -- it works fine and delivers the expected results.

> --- func.py -------------------------------
... cut ...
>
> # int func (int handle, int *numVars, char ***varNames, int **varTypes)
> func = c.CDLL('func').func
> func.restype = INT
> func.argtypes = [INT,PINT,PPPCHAR,PPINT]

I added this part to my program.

> # allocate storage for the out parameters
> numVars = INT()
> varNames = PPCHAR()
> varTypes = PINT()

I added this part also.

> print func(5,c.byref(numVars),c.byref(varNames),c.byref(varTypes))

I called the library routine.

> # numVars contains size of returned arrays.  Recast to access.
> varNamesArray = c.cast(varNames,c.POINTER(PCHAR * numVars.value))
> varTypesArray = c.cast(varTypes,c.POINTER(INT * numVars.value))

What does this cast? How do I know how I have to cast the objects returned 
from the library function?

What kind of objects do I get? I learned that the values of objects created 
by the ctypes module are accessed using object.value?

Best regards

Georg





More information about the Python-list mailing list