Reputation: 15793
I have a C library in which I defined a tree structure:
struct node {
int * info;
struct node *left;
struct node *right;
}
I want to make a call of C functions from python.
I wish to know what possibilities do I have to reconstruct the tree in python, that is built inside the C code using the quoted structure?
I intend to use ctypes. Do I have a better module for this?
Upvotes: 1
Views: 510
Reputation: 6026
Apache Thrift might be a better fit for you, which is a binary communication protocol developed by Facebook for various common programming languages including C++, Java, Python, Ruby ... etc (here is its wiki page for more details).
You might also interested in the following question asked in Stackoverflow, Thrift client-server multiple roles, which includes how the client calls a function in the server.
EDIT: As thrift only supports common primitive types, struct, and three container types (list<t1>, set<t1>, map<t1, t2>), you need to work with pointers. One way to work with is to use id to instance map. For example, you can assign an unique id for each node and use id to refer to the left and right node, and have an int to node map to fetch nodes by ids. Here is how the .thrift file of your node struct might look like:
struct Node {
// a thrift struct is composed of fields;
// each field has a unique integer identifier, a type, a name and an optional default value.
1: required i32 nodeId;
2: required i32 infoId;
3: required i32 leftNodeId;
4: required i32 rightNodeId;
}
For the function(s) you written in C and would like to invoke from python, you need to pack them into a thrift service. Here is the service of your function might look like (sorry, I didn't know your function interface at the time when I was editing this answer):
service TreeStructureService {
void processTreeNode(1: Node node);
}
If you would like to learn more about thrift, you might find Thrift: The Missing Guide useful.
Upvotes: 1
Reputation: 7177
You might check out cffi. It's kinda like ctypes, except it's more API-level than ABI-level. ctypes is ABI-level. It's also quite a bit younger than ctypes, and isn't yet included with CPython.
You could also try Cython, which allows you to pretty freely intermix C symbols and Python symbols using a Python-like syntax. You can use Cython to generate a .c file from a .pyx, where .pyx is quite a bit like .py. Of course, you then create a .so from your .c and import it into CPython. I've used m4 to create pure python and cython from the same file - it worked well.
Upvotes: 1