Variant datatype library for C

亡梦爱人 提交于 2019-11-28 13:34:05

GLib has implementation of generic value types in form of GValue: http://library.gnome.org/devel/gobject/unstable/gobject-Generic-values.html

Although I doubt that the original author still needs an answer (hopefully at least after 4 years), I wanted to add my 2ct.

First, let me state that the thing you ask for is called a sum-type and usually supported in functional languages (that is, it is rather a language design feature and not a library issue).

Second, it is highly doubtful that you will find a C-library for that case for the simple reason that any such library would support a fixed set of variants that probably does not fit your needs.

Howerver, for the sake of completeness, you might want to give msgpack a try.

I suggest reading the manual on the SQL database connector. The MySQL connector provides an API for obtaining the field types in the result.

You could create a Factory function that fills a structure based on the field type. Ironically, since C doesn't have Base types, you'll have to use a void * pointer and recast to the known structure type. (Even though void * is the type you are trying to get rid of.)

C is a very strong typed language, variants are not part of its philosophy. An union can't be a solution because you still have to choose the data type you want to use, it's typically used to store color codes on int and char[4].

If you look at the C-SQLite interface, this function is provided :

int sqlite_step(
  sqlite_vm *pVm,          /* The virtual machine to execute */
  int *pN,                 /* OUT: Number of columns in result */
  const char ***pazValue,  /* OUT: Column data */
  const char ***pazColName /* OUT: Column names and datatypes */
);

Data types are represented by char* and it's the developer's task to figure how to get types from these. I think any kind of variant type would have been better but it's just not C. C does not implement variants and is not meant to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!