c - 在 DLL 方法中返回 C 字符串

标签 c dll

我正在尝试创建一个 C 风格的 DLL 接口(interface),该接口(interface)接受输入 char * 并在执行一些翻译操作后分配输出 char * 。该函数的返回值是一个错误代码,因此不会用于返回 char *。

我以这种方式调用该函数:

char* output;
myfunc((char *) input.c_str(), &output);

函数定义为:

DLL_EXPORT int myfunc(char* input, char** output)
{
    string translation = translate(input);
    *output = (char *) malloc((translation.length()+1)*sizeof(char));
    strcpy(*output,(char *) translation.c_str());
}

这是实现此目的的正确方法吗?我是否造成了内存泄漏?

最佳答案

这是正确的,但您还需要提供另一个 DLL 函数来释放内存。您不能假设已加载 DLL 的可执行文件正在使用相同版本的 C 运行时库,因此,如果它尝试在返回的内存上调用 free,您最终可能会由于以下原因而损坏您的堆:不同运行时中 malloc/free 实现的差异。

您的 API 应该如下所示:

DLL_EXPORT int myfunc(char* input, char** output)
{
    ...
    *output = malloc(...);
    ...
}

DLL_EXPORT void myfunc_free(char *output)
{
    free(output);
}

另请参阅allocating and freeing memory across module boundaries .

关于c - 在 DLL 方法中返回 C 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9900081/

相关文章:

c - 如何使用Telnet 来测试我的socket 程序?

c - 为什么以及何时 malloc() 在 C 中不可用?

dll - 64 位操作系统上的 32 位 ActiveX DLL 问题

c++ - GetProcAddress 与所有加载的库

c - 跳过 IEEE 754 中的 "test for zero"检查

c - 定点表示的符号

c++ - 确定下载的文件是否与现有文件相同的函数

c++ - 无法导入 MFCreateDXSurfaceBuffer 函数

c++ - 从 dll 返回多个字符串

.net - 从 ASP.NET 页面启动 .NET DLL