写入传递给 DLL 的流

Writing into stream passed to a DLL

本文关键字:DLL 的流      更新时间:2023-10-16

我在写入流时遇到问题,该流作为 FILE* 传递给包含在 DLL 中的函数。编译器:Visual C++,所有版本 2005 到 2015。确切的错误各不相同;VS 2015版本如下。对于 Win32 和 x64 目标,该问题是相同的。

试图归结问题,请考虑以下函数:

#include <stdio.h>
void TestPrintf(FILE *TestFile)
{
    fprintf(TestFile, "Hello World");
}

现在,另一个函数将通过以下方式调用上述函数:

#include <stdio.h>
void TestPrintf(FILE *TestFile);
void AnyFunction( void )
{
    FILE *TestFile;
    fopen_s( &TestFile, "PrintTest.txt", "wt");
    TestPrintf(TestFile);
}

第一个函数是 DLL 的一部分。取决于属性/C/C++/代码生成 在编译 DLL 和包含调用方的程序期间,我收到以下错误消息:

为多线程调试编译的调用方(静态):
为多线程调试(静态)或多线程调试 DLL 编译的 DLL:

    Debug assertion failed   
    File: minkernelcrtsucrtsrcappcrtheapdebug_heap.cpp  
    Line: 980  
    Expression: __acrt_first_block == header  

为多线程(静态)编译的 DLL:

    Debug assertion failed in the same file as before, but now  
    Line: 892  
    Expression: is_block_type_valid(header->block_use)  

为多线程 DLL 编译的 DLL:

    Again another variant of the same. Now it is:  
    Line: 888  
    Expression: _CrtlsValidHeapPointer(block)  

为多线程调试 DLL 编译的调用方:
为多线程(静态)或多线程调试(静态)编译的 DLL:

    same messages as above  

为多线程 DLL 编译的 DLL:

    Yet another variant of the same. Now it is:  
    HEAP[FilePrintTest.exe]: Invalid address specified to RtlValidateHeap( 
    01060000, 0107B7A0 )

为多线程调试 DLL 编译的 DLL:

    This is error-free.  

为发布(多线程或多线程 DLL)编译的调用方:

all four versions of the DLL go error-free.  

VS版本之间的区别似乎是VS 2015首先按预期写入输出,然后崩溃,而VS 2005在写入输出时已经崩溃。

如果函数 TestPrintf 不在 DLL 中,而是在静态库中,则不存在此类问题(当然,会有关于库冲突的链接器消息,但测试程序仍然可以工作)。但是,不幸的是,我确实需要 DLL 中的写入函数,并且我必须能够从任何地方调用它。

上述所有内容也适用于调用方在控制台程序中并且流是标准输出的情况。

所以我的问题是:我这边有愚蠢的错误吗?如果没有,有没有办法解决这个问题?

我将不胜感激的建议!
马丁

请查看

fopen_s语法。 您正在使用指针前面的&传递FILE * *

尝试删除&符号:
fopen_s(TestFile, /*...*/);

您的TestFile已经是一个指针:

FILE * TestFile;

您的用法与 cppreference.com 提供的语法不匹配