2

I've a struct like this (I've coded the C struct like a C++ class to demonstrate what I am thinking; but I am working in C.):

//This is a source file
typedef struct _MyType
{
     void test() { printf("works!"); }
}MyType;

But I want to define my struct like that: (That not works)

//This is a header file
typedef struct _MyType
{
     void test();
}MyType;

//This is a source file
MyType::test() { printf("works!"); }

I've tried some more things but I can't do it again. (I want to use structs like classes)

How can I achieve this OOP-like separation in C?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275

1 Answers1

3

You cannot define functions inside struct in C programming.

However you can have function pointers inside struct

Something like this :-

typedef struct{
     void (*test)();
}MyType;


void test(MyType* self) { printf("works!"); }
int main()
{

    MyType *m =malloc(sizeof(MyType));
    m->test=test;
    m->test(m);

    free(m);
}
P0W
  • 46,614
  • 9
  • 72
  • 119
  • This is about as close as it gets to C++ if you stick to C. :) – Devolus Aug 18 '13 at 21:34
  • Well the instance struct could only have one pointer to a class struct which carries all function pointers to the methods. Then define some macros to handle the data and what you get is a simplified version of the Python-C-API... – dastrobu Aug 18 '13 at 21:36
  • I'll use (my) this implemention for a interface. Namely source will be in my program, header will be outside; a c++/c shared library will get my functions via this struct from my c application. I want to protect my c functions, also my functions will effect my c application. Any suggesstion about this? – MonoLightStudios Aug 18 '13 at 21:39
  • @MonoLightStudios Yes, use C++ :D – P0W Aug 18 '13 at 21:43
  • @MonoLightStudios: Or pass your data as struct (or array) and the callback function as function pointer, like you do for [qsort](http://linux-documentation.com/en/man/man3/qsort.html). – dastrobu Aug 18 '13 at 21:45