Passing a string from python to rust via SWIG

135 Views Asked by At

I'm working on building a library in rust that I think would be extremely useful in other languages. I would like to expose this functionality with idiomatic bindings to as many languages as possible with as little effort as I can get away with. Obviously SWIG is a great choice for this project.

I'm using a fantastic project called safer_ffi to produce the C interface to the rust library. It removes a lot of the error prone boiler plate on the rust side but also limits my options on exactly what the C interface looks like. Currently it represents strings with this C type:

typedef struct {
uint8_t * ptr;
size_t len;
} slice_boxed_uint8_t;

I can't for the life of me set the ptr member of the struct without causing a TypeError in python. My interface file is simply:

%module swig_example
%{
/* Includes the header in the wrapper code */
#include "swig_example.h"
%}

%include "stdint.i"
%include "cstring.i"

/* Parse the header file to generate wrappers */
%include "swig_example.h"

and I try and set up the struct with the following python:

def _str_to_slice(input: str) -> slice_boxed_uint8_t:
    slice = slice_boxed_uint8_t()
    slice.ptr = input
    slice.len = len(input)
    return slice

which produces the following error "TypeError: in method 'slice_boxed_uint8_t_ptr_set', argument 2 of type 'uint8_t '". I have tried all sorts of combinations of how to invoke it and how to generate the bindings. I've been walking through the generated C code but haven't found the issue yet. It looks like it understands that this pointer is a char but isn't making the connection that it is okay to use as a uint8_t*. I might have misunderstood some of the generated C code, I'm still not very deep on walking through that yet.

I did my best to include all relevant info but I know I might be missing some important context in this post so the code can be found here. The README.md points out here to find all relevant files, reasoning on how things are set up and I checked in the SWIG generated c and python files. This project is the smallest subset of my original project I could make to it easier for others to troubleshoot

Huge thank you to any help that anyone can provide!

0

There are 0 best solutions below