在 api.h
typedef void* hidden_my_type;
void do_something(my_type x);
在 core.c 中
struct _my_type
{
int a;
}
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x; /*Don't understand is that correct way to do, as I'm getting segmentation fault error */
printf("Value: %d\n", x->a);
}
我认为的其他方式,
struct *_my_type x = (struct _my_type *)malloc(sizeof(struct _my_type));
void_x = x
printf(Value: %d\n", x->a);
但我仍然收到段错误错误。
好的,这里是 void*.... 的问题。
例如在 core.c
void init_my_type(hidden_my_type a)
{
my_type *the_a = malloc(...);
a = the_a // <<<<<<<<<<<<<<<<<<<<<<<<<<<< is this correct?! a is void* and the_a // is original type
pthread_cond_init(&the_a->...);
.. (in short any other methods for init ..)
}
void my_type_destroy(my_hidden_type x)
{
my_type *the_x = x;
pthread_detroy(&the_x-> ...);
}
在 main.c
test()
{
my_hidden_type x;
init_my_type(x);
....
my_type_detroy(x);
}
这它自己应该失败。就像在 main.c 测试函数中一样, x 是 void* ... init 将分配,但在销毁时我再次传递 void* .. 这可以是任何东西!
编辑(为我解决)
在 api.h
typedef void* hidden_my_type;
void do_something(my_type x);
在 core.c 中
struct _my_type
{
int a;
}
void init_hidden_type(hidden_my_type void_p_my_type)
{
struct _my_type *real_my_type = (struct _my_type *)malloc(sizeof(struct _my_type));
//--- Do init for your type ---
void_p_my_type = real_my_type;
}
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x;
printf("Value: %d\n", x->a);
}