在 C# 中调用此 C 函数的正确语法是什么?该函数使用指针和数组

What is the correct syntax for calling this C function in C#? The function uses pointers and arrays

我正在尝试从用 C 编写的 DLL 中调用一个函数。我需要在 C# 中调用该函数,但我相信我 运行 遇到了语法问题。我有一个使用 Python 中的 ctypes 库的工作示例。不幸的是,DLL 需要 运行 的加密狗,所以现在我正在寻求有关 C、Python 和 C# 之间语法中任何明显差异的帮助。

C 函数的格式为

int (int nID, int nOrientation, double *pMTFVector, int *pnVectorSize ); (我真的不熟悉指针,PDF 文档中的星号被空格包围,所以我不确定星号应该附加到什么地方)

这段代码的作用是接受 nID 和 nOrientation 来指定图像中的特征,然后用值填充数组。该文档描述了以下输出:

out; pMTFVector; array of MTF values, memory is allocated and handled by application, size is given by pnVectorSize

in,out; pnVectorSize maximum number of results allowed to store in pMTFVector, number of results found and stored in pMTFVector

实际有效的python代码是:

lib=cdll.LoadLibrary("MTFCameraTester.dll")
lib.MTFCTGetMTF(c_uint(0), c_int(0), byref((c_double * 1024)()), byref(c_uint(1024)))

我试过的代码是:

 [DllImport("MTFCameraTester.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public extern static MTFCT_RETURN MTFCTGetMTF(UInt32 nID, int orientation, double[] theArray, IntPtr vectorSize);

        double[] myArray = new double[1024];
        IntPtr myPtr = Marshal.AllocHGlobal(1024);
        returnEnum = MTFCTGetMTF(0, 0, myArray, myPtr);

当代码为运行时我的returnEnum-1,这在文档中被指定为错误。这是我遇到的最好的结果,因为在尝试 refout

的不同组合时我遇到了很多 Stack Overflow 错误

你快到了。最后一个参数是我认为的问题。像这样尝试:

[DllImport("MTFCameraTester.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static MTFCT_RETURN MTFCTGetMTF(
    uint nID,
    int orientation,
    [Out] double[] theArray, 
    ref int vectorSize
);

....

double[] myArray = new double[1024];
int vectorSize = myArray.Length;
MTFCT_RETURN returnEnum = MTFCTGetMTF(0, 0, myArray, ref vectorSize);

有效的 VB.NET 解决方案是:

   <DllImport("MTFCameraTester.dll", CallingConvention:=CallingConvention.Cdecl)> _
    Function MTFCTGetMTF(ByVal id As UInt32, ByVal orientation As UInt32, ByRef data As Double, ByRef len As UInt32) As Integer
    End Function

    Dim ret As Integer
    Dim dat(1023) As Double
    Dim len As UInt32 = 1024
    ret = MTFCTGetMTF(0, 0, dat(0), len)

看来我必须将数组的第一个元素传递给 C 函数,然后由它处理其余部分。