In python, C needs to supplement the efficiency in some cases. in practical applications, some data interaction is required. python can call C. the following demonstrates how to call a standard Function C in Python. pass a structure pointer. the allocated memory data in C is transmitted. I hope it will help you learn python.
1 test. c
# Include <stdio. h>
# Include <stdlib. h>
Typedef struct {
Unsigned char words [10];
} Keywords;
Typedef struct {
Keywords * KWS;
Unsigned int Len;
} Outstruct;
Int test (outstruct * o ){
Unsigned int I = 4;
O-> KWS = (keywords *) malloc (sizeof (unsigned char) * 10 * I );
Strcpy (o-> KWS [0]. words, "Test 1 ");
Strcpy (o-> KWS [1]. words, "Test 2 ");
O-> Len = I;
Return 1;
}
2 compile
Gcc-C
-FPIC-O test. O test. c
Gcc-shared test. O-o
Test. So
3 test. py
From ctypesimport
*
Class keywords (structure ):
_ Fields _ = [
('Word', c_char * 10),]
Class outstruct (structure ):
_ Fields _ = [
('Done', pointer (keywords )),
('Len', c_int),]
Libc = cdll ("./test. So ")
Libc. Test. argtypes = [pointer (outstruct)]
O = outstruct ()
Ret = libc. Test (byref (o ))
Print O. KWS [0]. words;
Print O. KWS [1]. words;
Print O. Len
4. Test Results
B 'test 1'
B 'test 2'
4