The right type for handles in C interfaces

后端 未结 4 763
名媛妹妹
名媛妹妹 2020-12-29 08:11

I\'m creating a C api that hides some functionality in a DLL file.

Since everything is C++ on the inside most of the functions works against handles which maps direc

相关标签:
4条回答
  • I think you can just declare, but not define, the source structures:

    struct MyType1;

    typedef struct MyType1* MyType1Handle;

    0 讨论(0)
  • 2020-12-29 08:52

    Use an opaque struct. This is a good idea in many cases when defining the interface to a library in C: it improves modularity, hides unnecessary detail

    As JamieH said, you get an opaque struct by declaring - but not defining - a struct. It's perfectly valid to have, and pass, pointers to the opaque struct into the libraries functions as arguments and return them as values. Users of library however cannot create or modify objects of the opaque struct since it's size and content is unknown.

    The C standard library, and many others, already use this approach so it should be familiar. The cannonical example is the use of FILE *: fopen() creates and initialises the struct and returns a pointer to it, fclose() cleans up and releases it and all other i/o functions get their context from the passed in FILE *.

    0 讨论(0)
  • 2020-12-29 08:55

    If you look at how Microsoft defines it's winapi handles (winnt.h) it actually looks like this:

    struct HWND__ { int unused; }; typedef struct HWND__ *HWND
    

    in fact they have a macro for this:

    #define DECLARE_HANDLE(name) struct name##__{int unused;}; typedef struct name##__ *name
    

    so.. this seems to be a common practice to do so. Unfortunately I can't make another suggestion except this one, which you already mentioned, but I hope it helps you anyway.

    0 讨论(0)
  • 2020-12-29 08:56

    Similar topic : Handles Comparison: empty classes vs. undefined classes vs. void*

    0 讨论(0)
提交回复
热议问题