我想从我的 API header 中隐藏 OpenSSL RSA
结构要求,所以我这样做了:
// api.h
typedef struct RSA_key * RSA_key_ptr;
RSA_key_ptr get_rsa_key();
void free_rsa_key(RSA_key_ptr key);
// api.c
#include <openssl\rsa.h> // RSA struct
typedef RSA RSA_key;
RSA_key_ptr get_rsa_key()
{
//return RSA_new();
return (RSA_key_ptr)RSA_new();
}
void free_rsa_key(RSA_key_ptr key)
{
//RSA_free(key);
RSA_free((RSA*)key);
}
我的问题是,每次我在 api.c
中引用 RSA
指针时,我都需要从RSA_key_ptr
以防止不兼容的指针类型警告。
我想找到更优雅的方式来:
- 避免显式转换
- 避免警告
最佳答案
你需要类型转换。 struct RSA_key
是一种新类型,不是由typedef RSA RSA_key;
定义的。它是没有定义的不相关结构的名称。您只能处理指向它的指针,并将其他结构指针转换为它。
隐藏实现细节(除非多余的 typedef RSA RSA_key;
)是一个不错的技术。类型转换是很好的标准 C。
如果您发现自己处于强制转换表达式自身周围需要太多括号的情况,那么一个小的实用函数或宏可能有助于缓解它:
static inline RSA* as_rsa(struct RSA_key* rsa_key)
{ return (RSA*)rsa_key; }
static inline struct RSA_key* as_rsa_key(RSA* rsa_key)
{ return (struct RSA_key*)rsa_key; }
关于c - 省略类型定义结构的显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55916547/