Printf with size_t using FFI

To print an integer size_tin C s printf, formatting conversion %zu.

However, when I use printfc %zu, calling the C function in Haskell via FFI prints zuinstead of the integer. How to solve this?

Minimal example

zu.c file

#include <stdio.h>

void printzu(){
    size_t x = 666;
    printf("x=%zu", x);
}

lib.hs module

{-# LANGUAGE ForeignFunctionInterface #-}
module Lib
  where
import Foreign

foreign import ccall unsafe "printzu" printzu' :: IO ()

Test

Prelude> import Lib
Prelude Lib> printzu'
x=zu
+4
source share
3 answers

printf() C, . , , , , . %zu , , C99.

, , MSVCRT.DLL, , MS Visual C 6. , MinGW , C- . , , , C89/C90.

size_t , unsigned long :

size_t x = 666;
printf("x=%lu", (unsigned long)x);

,

  • size_t, unsigned long ( , , 64- LLP64, , win64)
  • , unsigned long. 4G (2 32), unsigned long.

, . printf() , printf(const char *fmt, ...), , .


MSVCRT.DLL, C99 , , inttypes.h . Windows ( - , C99, ).

+4

"%zu" , - , .

size_t sz = foo();
printf("%lu\n", (unsigned long) sz);  // risk of truncation.

, uintmax_t unsigned long long, "%zu" , "%ju" "%llu" .

.

printf("%lX%08lX\n", 
    (unsigned long) (sz/0x10000u/0x10000u), (unsigned long) (sz & 0xFFFFFFFFu));

// remote truncation risk remains.
printf("%lu%09lu\n", 
    (unsigned long) (sz/1000000000u), (unsigned long) (sz%1000000000u));

, .

+1

I would like to suggest another approach to working with systems that do not comply with the C99 / C11 standards but provide 64-bit or wider types.

Import and enable stdint.h/inttypes.h, designed to connect older systems to the new C99 standards.

Example: C99 header stdint.h and MS Visual Studio

Then add to the wide type available, although they

#if SIZE_MAX > ULONG_MAX
// Include from the standard location or wherever the imported included files are saved.
#include <stdint.h>
#include <inttypes.h>

void printzu(){
    size_t x = 666;
    printf("x=%" PRIuMAX "\n", (uint_max_t) x);
}

#else
void printzu(){
    size_t x = 666;
    printf("x=%lu\n", (unsigned long) x);
}
#endif
+1
source

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


All Articles