0

Below is the structure that I had defined in the C dll:

//structure.h
#include<stdio.h>
typedef struct Point 
{
    double x, y;
} Point;

And the .c file is as follows:

//structure.c
#include<stdio.h>
#include "structure.h"
#include <math.h>

/* Function to calculate hypotenuse of a triangle */
 __declspec(dllexport) double distance(Point *p1, Point *p2)
{ 
    return hypot(p1->x - p2->x, p1->y - p2->y);
}

Using ctypes in python, I had written a script as below which can have access to the C DLL:

//structure.py
import ctypes as C
from ctypes import *

class Point(C.Structure):
    _fields_ = [('x', C.c_double),
        ('y', C.c_double)]
mydll=C.cdll.LoadLibrary('structure.dll')    
distance=mydll.distance
distance.argtypes=(C.POINTER(Point),C.POINTER(Point))
distance.restype=C.c_double
p1=Point(1,2)
p2=Point(4,5)
print(mydll.distance(p1,p2))

As this is just a very small structure having very less variables, it is easy to write the python script along with the C file.

But in case of a project having 1000's of structure and also infinite number of variables in them, is there a way by which this duplicate effort of writing the structures in ctypes as well can be reduced?

Or is there some tool available in Python that can directly convert C header file to Python structure?And also is there is some python module or tool which can convert the C structure directly to ctypes structure?

P.S.- I want all of this to be implemented in Windows environment.

user39602
  • 339
  • 2
  • 5
  • 13
  • Instead of doing byte and bit manipulation in python, you could use a text-based transfer like json. – stark Jul 29 '16 at 12:02
  • Alternatively, 1) write a Python extension that uses the dll, or 2) write the DLL as a Python extension, or 3) use a third file from which you generate both the C header and the Python glue. –  Jul 29 '16 at 12:09
  • 2
    I [already told you](http://stackoverflow.com/q/38561074) about ctypesgen for ctypes and recommended using CFFI instead of ctypes. CFFI includes a C parser to automate processing headers, and unlike ctypes it can operate in either an ABI (binary) or API (compiler) mode. – Eryk Sun Jul 29 '16 at 12:31
  • @eryksun Perhaps you should write an answer for that question then. – Jonathon Reinhart Jul 29 '16 at 15:14
  • Pardon me everyone for raising a similar question again. I was in utter need of getting a solution to the problem so that's why raised the question in a different manner. – user39602 Jul 29 '16 at 16:30
  • @eryksun I will be really thankful to you if you post a small example program to do the same as I had searched about cffi but didn't understand much about it . – user39602 Jul 29 '16 at 16:32

0 Answers0