编程语言
首页 > 编程语言> > C#使用FILE *参数调用C函数

C#使用FILE *参数调用C函数

作者:互联网

我在C库的结构中定义了以下函数指针:

struct SOME_STRUCT {
    [...]
    uint8_t(*printinfo) (SOME_STRUCT * ss, FILE * hFile);
    [...]
}

此函数将一些数据写入文件句柄hFile,我想从C#调用它.在C#中,我有:

[StructLayout(LayoutKind.Sequential)]
public struct SomeStruct
{
    [...]
    public printinfoDelegate printinfo;

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate byte printinfoDelegate(IntPtr ss, IntPtr hFile);
    [...]
}

我使用以下代码来调用该函数:

SomeStruct sStruct = [...];
String output;

using (FileStream stream = new FileStream(tmpFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
    IntPtr structPtr = Marshal.AllocHGlobal(Marshal.SizeOf(sStruct));
    Marshal.StructureToPtr(sStruct, structPtr, false);

    byte result = sStruct.printinfo(structPtr, stream.SafeFileHandle.DangerousGetHandle());

    stream.Seek(0, System.IO.SeekOrigin.Begin);

    using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
    {
        output = reader.ReadToEnd();
    }
}

但是我无法使其正常工作.我怀疑问题是我不能仅仅将文件流中的句柄作为FILE *传递.任何帮助将不胜感激…

解决方法:

.NET中的句柄是指Win32 HANDLE(或HINSTANCE等),例如CreateFile函数返回的值.另一方面,FILE *是C运行时库的一部分,并通过调用fopen函数返回.

因此,如果要使用带有FILE *参数的函数,则也必须P /调用fopen方法,例如here.

标签:c-3,c,pinvoke
来源: https://codeday.me/bug/20191122/2056641.html