Skip to content

#sizeof fails on non-typedef'd structs #95

Closed
@RyanGlScott

Description

@RyanGlScott

I am trying to call #sizeof on a struct not created with typedef (which is surprisingly common, e.g., sockaddr_rc from the BlueZ library). Here is a simple example:

// struct.h
#ifndef WTF_H
#define WTF_H

struct foo {
    int x;
    int y;
    int z;
};

#endif
-- Struct.chs
{-# LANGUAGE ForeignFunctionInterface #-}
module Struct where

#include "struct.h"

fooSize :: Int
fooSize = {#sizeof foo #}

Running c2hs Struct.chs will fail with the error message:

c2hs: Errors during expansion of binding hooks:

Struct.chs:8: (column 20) [ERROR]  >>> Unknown identifier!
  Cannot find a definition for `foo' in the header file.

A simple workaround is to manually typedef it elsewhere (e.g., typedef struct foo foo_t). However, it doesn't feel like this should be necessary, since c2hs has no problem recognizing non-typedef'd structs elsewhere. For example, c2hs preprocesses this with no problem:

{-# LANGUAGE EmptyDataDecls, ForeignFunctionInterface #-}
module Struct where

#include "struct.h"

import Foreign.C.Types
import Foreign.Ptr
import Foreign.Storable

data Foo
{#pointer *foo as FooPtr -> Foo #}

fooMutate :: FooPtr -> CInt -> IO ()
fooMutate = {#set foo.x #}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions