c - 将从 C# 接收到的文件 byte[] 数组写入 C dll 中的文件

标签 c dll dllexport char-pointer

我刚刚创建了一个简单的 PDF 文档,其中包含单词“Test”,并在 C# 控制台应用程序中创建了一个字节流:

buff = File.ReadAllBytes(<Path of File>);

文件大小约为 9,651 字节。我还创建了一个 Win32 C dll,它导出一个函数,该函数将文件字节数组和字节数组的长度作为参数,在 C# 中使用以下声明:

[DllImport("<path to dll>", CallingConvention = CallingConvention.Cdecl)] public static extern int file_data(byte[] byteArray, int length);

导出C dll中的方法如下:

#define FILEDATA_API __declspec(dllexport) FILEDATA_API int file_data(char *byteArray, int size);

然后我调用了ret = file_data(buff, buff.length) ;在C代码中,将接收到的字符指针逐个字符地直接写入临时文件,如下所示:

    while (length> 0)
    {
        fprintf(outFile, "%c", *fileData); //fileData is the actual byte array received from C# Code
        fileData++;
        length--;
    }

但是问题就出现在这里,将字节数组逐字符转储到文件的 C 代码生成了一个大小为 9,755 字节的文件。其中的大部分内容似乎看起来都是正确的,除了引入的一些新行(据我所知,可能是一些附加数据),这会导致 PDF 文件损坏,并且此转储版本无法在 Adob​​e 中打开。有人可以提供一些关于我可能出错的地方的指示吗?我无法使用%s in fprint因为 PDF 中字节数组的某种组合会导致 C 中以 null 结尾的字符串,然后转储出的数据比我预期的还要少。

谢谢。

更新:

  1. 所需的行为是从 C# 接收到的文件字节数组 当使用 C 代码写入文件时,应该使文件打开 在 Adob​​e 中成功。
  2. 问题中出现的代码应该是 足以让某人生成 win32 dll,只需编写 输出 char 指针到文件,但我添加了更多细节。

最佳答案

您可能在不使用 b 模式标志的情况下调用 fopen。将 b 附加到模式说明符:

FILE *outFile = fopen("file.txt", "wb")

来自this site (强调我的):

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

根据我的经验,Windows 上的这种“转换”至少会将 \n 更改为 \r\n

关于c - 将从 C# 接收到的文件 byte[] 数组写入 C dll 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33957933/

相关文章:

c# - 在 C# DLL 中为 COM INTEROP 注册 .tlb 文件时出错

c - 我应该把 DLL 的声明放在哪里? + 如何在另一种语言中使用它 [C]

dll - 从 DLL 导出生成 header

c++ - 不能使用隐式链接的 .dll 中的类

c - __declspec(dllimport) 和外部 (OBS)

python - 如何知道 nquad 调用的 C 函数中的维数?

c - 错误: dereferencing pointer to incomplete type when compil C program

c# - 带有 RGiesecke.DllExport 的 C# DLL 中没有函数

c - 从用户读取 "n"行并将其写入 C 中的文本文件的程序

c - 如何读取系统的输出 ('ls' )?