Writing an API: what a pen should be

Suppose we are writing a library that implements some API. Lib creates some resources (connections / internal data structures / independently) and returns a handle, which is then used for further calls.

What are the recommended ways to represent a descriptor?

  • Should it be a raw pointer to a dedicated internal data structure when creating a session?

  • If this is the case, how can I protect lib in case the API function called after the closemethod that releases the data descriptor has pointed to?

If the descriptor is an abstract number (for example, the key in the map is "handle" β†’ "obj"), will this not affect performance?

What other approaches are possible? Which one to choose?

If someone worked on the API, can you share your experience on this?

The question is too broad and abstract, but I am currently working on very similar tasks and just don’t know how to solve this problem.

I looked through the sources sqlite3, their descriptor is just a pointer to a dynamically distributed structure, they set some magic numbers when opening a connection and close it, and checking that the descriptor is correct consists in checking these magic numbers. Is it safe enough?

+4
source share
4 answers

"close" -, NULL.

interface.h:

typedef struct handle_internals * Handle;

int handle_open(/* out */ Handle * phandle, ..);
int handle_close(/* in out */ Handle * phandle)

int handle_func1(Handle handle, ..);
...

implementation.c:

...

#include "interface.h"

...

struct handle_internals
{
  ...
}

int handle_open(Handle * phandle, ..)
{
  if (NULL == phandle)
  {
    errno = EINVAL;
    return -1;
  }

  *phandle = malloc(sizeof ** phandle);

  ...

  return 0;
}

int handle_close(Handle * phandle)
{
  if (NULL == phandle)
  {
    errno = EINVAL;
    return -1;
  }

  free(*phandle);
  *phandle = NULL;

  return 0;
}

int handle_func1(Handle handle, ..)
{
  if (NULL == handle)
  {
    errno = EINVAL;
    return -1;
  }

  ...

  return 0;
}
+4

: " ?" .

Sudoku, , , , , .

, , , .

.

+3

- , , . , ( API) ( ) , , ..
API- , . , , , - , Windows, , , . , Windows:

1) HWND - .
2) HINSTANCE - OS (kernal) .
3) HMENU - .
4) HANDLE - WINAPI. , , .

, .

, 32- , . , , , , . , .

, API?

, ? , lib . , ( ).

lib , API close?
API:
1) close handle 0 NULL ( , )
2) API /-NULL .
3) API , API, . ( 0. ?) API.

(, "handle" β†’ "obj" ), ?
, , ...
, - , , , .

+3

, , . :

typedef struct SomeInternal* Handle;

SDK , , , . , SDK.

, , - (). , , . qsort vs. std::sort ++ std::sort, T, qsort 2-3 - . qsort - , , - ( 30 '). , , , , .

, , , , , ABI , . , .

, lib , API- close, ?

( , , C , ), , , - close destroy, , , , . , , .

+1

All Articles