假设我有 2 个 dll。第一个,我从 openbsd.org 获得关于使用 strlcpy 函数避免缓冲区溢出的代码,第二个是再次使用 gtk-glib-2.0 dll 导出函数以避免缓冲区溢出“g_snprintf”,而不是标准调用 c 函数 snprintf。当我想返回缓冲区字符串值时,问题就出现了,这样我就可以将此代码制作为 dll 并轻松地从 python 语言调用这两个函数。这是片段:
#include <stdio.h>
#include "dlfcn.h"
#include <sys/types.h>
#include <string.h>
#define lib "strlcpy.dll"
#define func "strlcpy"
#define lib2 "libglib-2.0-0.dll"
#define func2 "g_snprintf"
char* returnMsg(char *buff, unsigned long n, char *msg)
{
int (*g_snprintf)(char *string, unsigned long n, char const *format,char *msg);
void *handle2;
int errorno;
handle2 = dlopen(lib2, RTLD_LAZY);
if (!handle2){
printf("\nerror opening second dll\n");
return 1;
printf("got it at second dll: %p",handle2);
g_snprintf = dlsym(handle2, func2);
if (!g_snprintf)
printf("error getting g_snprintf symbol..");
return 1;
if ((errorno= g_snprintf(buff, n, "%s",msg)) !=0)
printf("error cannot use g_snprintf..");
return 1;
dlclose(handle2);
return buff;
}
int main()
{
char iv[32];
char *msg,*l;
int k;
unsigned int g;
char buff[16];
size_t (*strlcpy)(char *dst, const char *src, size_t siz);
void *handle;
handle = dlopen (lib, RTLD_LAZY);
if (!handle) {
printf("error cannot open library..");
return 1;
}
printf("opening dll at %p\n", handle);
strlcpy = dlsym(handle, func);
if (!strlcpy) {
printf("error cannot find desired exported function..");
return 1;
}
printf("got it, strlcpy function at %p\n",strlcpy);
g = 16;
msg = "this is messages boy!";
memset(iv,0,sizeof(iv));
strlcpy(iv,msg,sizeof(iv));
for(k=0;k<strlen(msg);k++){
printf("%c",iv[k]);
}
printf("\n%ul",g);
printf(" and %d",sizeof(iv));
l = returnMsg(buff, sizeof(buff),msg);
printf("%s",l);
dlclose(handle);
}