c - 如何在c中返回这个缓冲区值?

标签 c

假设我有 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);
} 

最佳答案

if ((errorno= g_snprintf(buff, n, "%s",msg)) !=0)
    printf("error cannot use g_snprintf..");
    return 1;

男孩,这不是 python 。您需要括号 {}

关于c - 如何在c中返回这个缓冲区值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10040738/

相关文章:

c - 我应该学习汇编语言或 C 来理解 "real programming"是如何工作的吗?

c - 解析源代码

c - 从链表中删除和返回值

c - C语言中如何在中间插入节点

c - gcc 未定义对 dbus_* 的引用

c - 仅分配 ~1400MB 后空间不足,而之前的可用空间明显更大

c++ - 交换宏的值

子函数 : How do I know what to fix? 中的 C 段错误 什么是段错误?

c - 在 C 中打开文件 - 为什么它不加载所有矩阵或删除\n?

c - 程序在NetBeans中运行时无法输入数据