To use SWIG to connect your Python script with C project, the first step is to create an interface file that includes the C functions that will be called by Python (i.e., interface functions), such as buffer.i as follows.
/* File: buffer.i */
%module buffer
%{
#define SWIG_FILE_WITH_INIT
#include "buffer.h"
%}
void wr(int idx, unsigned int val);
unsigned int rd(int idx);
It's a good practice to keep the interface simple, and leave the complexity to C running in the background. Accordingly, you can manually create a C header file (buffer.h) and implementation file (buffer.c), as follows.
Here is buffer.h
/* File: buffer.h */
#include <stdint.h>
void wr(int idx, unsigned int val);
unsigned int rd(int idx);
Here is buffer.c
/* File: buffer.c */
#include "buffer.h"
#define BUF_SIZE 32
unsigned int buf[BUF_SIZE];
void wr(int idx, unsigned int val) {
buf[idx%BUF_SIZE] = val;
}
unsigned int rd(int idx) {
return buf[idx%BUF_SIZE];
}
And you'll need a setup file (setup.py):
#!/usr/bin/env python
"""
setup.py file for SWIG buffer
"""
from distutils.core import setup, Extension
buffer_module = Extension('_buffer',
sources=['buffer_wrap.c', 'buffer.c'],
)
setup (name = 'buffer',
version = '0.1',
author = "SWIG Docs",
description = """Simple swig buffer from docs""",
ext_modules = [buffer_module],
py_modules = ["buffer"],
)
Now you can use SWIG to build the project by issuing the following commands:
$ swig -python buffer.i
$ python setup.py build_ext --inplace
The above commands will automatically generate buffer.py, which give you the caller framework (on Python side). Open this file, you'll see _buffer.wr and _buffer.rd already being created. In order to convert a very long int (Python style) 32 bits at a time and keep it in a C array, you can add a wrapper function in buffer.py, which calls the automatically generated Python function wr multiple times:
def wr1(args):
for n in range(0, 32):
val = args & 0xffffffff
wr(n, val)
args >>= 32
if args == 0:
break
Now you can run Python. Here is what you see when you run it:
>>> import buffer
>>> buffer.wr1(0x12345678deadbeef)
>>> hex(buffer.rd(0))
'0xdeadbeef'
>>> hex(buffer.rd(1))
'0x12345678'
inputto be? It's easy if it's a list of ints.