我在C(不是C ++)中实现了一个存储指向数据的链接列表。我希望它的函数有多个声明(提供类型安全性),但是它们每个都链接到相同的定义(因为指向不同数据类型的指针之间没有实际差异,因此使用相同的代码会减少空间)。
有没有人对如何实现这一点(或更好的方法)有任何想法?便携式解决方案显然是最好的,但我真的只需要在GCC中运行的东西。
答案 0 :(得分:1)
我相信你可以使用typedef来实现这个功能原型和
将通用解决方案(处理void*
s)转换为特定原型。这应该是安全的编译,因为所有指针都是相同的大小。
考虑这个例子:
do_something.h
:
typedef void (*do_something_with_int_t)(int *i);
extern do_something_with_int_t do_something_with_int;
typedef void (*do_something_with_string_t)(char *s);
extern do_something_with_string_t do_something_with_string;
do_something.c
#include "do_something.h"
void do_something_generic(void* p) {
// Do something generic with p
}
do_something_with_int_t do_something_with_int =
(do_something_with_int_t)do_something_generic;
do_something_with_string_t do_something_with_string =
(do_something_with_string_t)do_something_generic;
只要do_something_generic
真正与数据类型无关(即真的与p
指向的无关),那就没关系。
答案 1 :(得分:0)
#include <stdio.h>
struct common_type {
int type;
};
struct type1 {
int type;
int value;
};
struct type2 {
int type;
char* p;
};
int func(void *para) {
switch (((struct common_type*)para)->type) {
case 1:
printf("type1,value:%d\n",((struct type1*)para)->value);
break;
case 2:
printf("type2,content:%s\n",((struct type2*)para)->p);
break;
}
}
int main() {
char *s = "word";
struct type1 t1 = {1,1};
struct type2 t2;
t2.type = 2;
t2.p = s;
func((void*)&t1);
func((void*)&t2);
}
答案 2 :(得分:0)
如果它是C(不是C ++),那么下面的工作就可以了。您可以根据需要调整概念。
<强> tt.h 强>
typedef struct {
int ii;
} Type_1;
typedef struct {
int ii;
} Type_2;
int foo_1(Type_1* ptr) __attribute__((alias("foo")));
int foo_2(Type_2* ptr) __attribute__((alias("foo")));
<强> tt.c 强>
#include <stdio.h>
#include "tt.h"
int main() {
Type_1 t_1;
Type_2 t_2;
foo_1(&t_1);
foo_2(&t_2);
}
int foo(void* arg) {
printf("foo: %p\n", arg);
}