c - API returning a structure -


what's best solution when:

  • our api returns structure user
  • we want user able read contents
  • we don't want user change it, because might passed other api function , contents should correct?

your function can return pointer const structure. then:

  • the caller not permitted modify structure through pointer const structure. c implementation should enforce rule.
  • if caller passes pointer const structure function in api, c rules permit function convert pointer const structure pointer non-const structure. if structure not defined const (e.g., created non-const, pointer converted pointer const structure), function permitted modify structure through newly converted pointer non-const structure.
  • the c rules permit caller same conversion , modification. obviously, caller should not this, , relying on not so. thus, technique prevents inadvertent modifications through returned pointer not prevent malicious modifications through converted pointer.

to go further that, can provide caller incomplete declaration of structure, 1 reveals name (as in struct foo;) , not define contents (as in struct foo { int x;… };). when caller has incomplete declaration of structure, can receive pointer structure, , can store , pass argument, cannot use access structure (except abnormal means, such converting pointer type or providing own definition of structure).

if caller have incomplete declaration of structure must able use contents of structure, must provide additional functions accept pointer structure parameter , return information inside structure.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -