Method for communication between C and Python

xiaoxiao2021-03-05  56

These days are doing a project, the front end uses Python to make it easy to develop, the bottom layer uses C to write, high efficiency, fast speed. This involves communication issues between the two. I checked the relevant documentation and found the following solutions:

Using standard data representations, such as XML or XDR, then have their own corresponding libraries at both C and Python, can interpret these data, naturally, you can communicate. Define a structural object in C, package it into binary form (Python interpret it as a string), then use the Pack function of the Struct module in Python, which is involved in a problem of resolving the format, one The simple way is to define the corresponding two-set data structure at both ends of C and Python, which have their own pack and unpack functions, which can analyze the intermediate results --- binary strings, so that communication can be implemented. In the end of Python, you can also use the Array module, processing the type unified data, especially convenient, sometimes it is better than using the Struct module! Using an XML file contains the structures defined in c, then parsing this XML file on the end of Python, naturally, know how the Struct object in each C is parsed, so that it is better. Use the third party library, I know, there is boost.python and ctypes, and I don't have it.

I used the second way when I realized, and I will take an example:

There is such a structure in C:

TYPEDEF STRUCT TEST_TAG {Int A; Int B;} Test_t;

Char * test_pack (test_t * ptr) {char * p = null; p = (char *) malloc (sizeof (test_t)); Memcpy (p, ptr, sizeof (test_t)); return p;}

TEST_T * TEST_UNPACK (CHAR * PTR) {Test_t * p = NULL; P = (Test_t *) Malloc (SIZEOF (Test_t)); Memcpy (p, ptr, sizeof (test_t)); Return P;}

There is such a corresponding data structure in the Python side:

Class test: format = '2i' members = ('a', 'b') DEF __INIT __ (Self): for item in test.members: self.__ dict __ [item] = - 1 def pack (self, order = '@ @ @ s '): Return Struct.Pack (Order Test.Format, Self.a, Self.B)

DEF PACK2 (Self, ORDER = '@'): bin = array.Array ('l') for item in test.members: bin.append (self .__ dict __ [item]) IF (sys.byteorder == 'little' And ORDER == '>') or (sys.byteorder == '): bin.byteswap () return bin.tostring () Def unpack (self, data, order =' @ ' : (Self.a, self.b) = struct.unpack (ORDER TEST.FORMAT, DATA) DEF UNPACK2 (Self, Data, ORDER = '@'): bin = array.Array ('L') bin. FromString (DATA) for i, item in enumerate: self.__ dict __ [item] = bin [i]

You can then use these functions to communicate.

转载请注明原文地址:https://www.9cbs.com/read-36694.html

New Post(0)