How to create a cross-platform interface with SWIG?

I am wrapping a library using SWIG (Python as target). Library functions contain parameters with data types "uint32_t", "uint8_t", etc. I want to make the interface as cross-platform as possible, so I want to use the original function signatures in my interface.i file. For instance:

 uint32_t func(uint32_t a, uint32_t b); 

The problem I'm trying to solve is that SWIG will not recognize the parameter as an integer if there is no typedef in the uint32_t type. Right now I am using this in the interface file:

 typedef unsigned uint32_t; 

Removing this typedef line will cause the function to not be called from the Python target binding:

 >>> mylib.func(2, 2) TypeError: in method 'func', argument 1 of type 'uint32_t' 

The previous typedef is fine on my local machine, but may differ on another compiler / platform. Using the %include "stdint.h" directive %include "stdint.h" will throw an error on SWIG:

 /usr/include/stdint.h:44: Error: Syntax error in input(1). 

This makes sense because SWIG is not a fully functional compiler and cannot fully appreciate all of #ifdef in this header.

How can I correctly combine SWIG with the data types that the compiler selects in the stdint.h header? Does it make sense to have strict adherence to the correct data types, or just typedef all intX_t to long in order?

+6
source share
2 answers

If you want to use these types in your SWIG interface file, you can do something like:

 %module test %include "stdint.i" uint32_t my_function(); 

The existing SWIG interface has the correct typedef for your system.

+11
source

You have to force typedef because uint32_t is not a cross platform, not a cross compiler. uint32_t is the C99 standard, but many compilers have decided not to fully implement this standard. You may have an inclusion to override in the cross-compiler your project types:

http://www.azillionmonkeys.com/qed/pstdint.h

It is worth reading the introduction of the header linked above. You can use this include instead of stdint.h.

You can also read this question:

Cross-platform primitive data types in C ++

0
source

Source: https://habr.com/ru/post/915055/


All Articles